Skip to content

Commit 66615d0

Browse files
lvan100lianghuan
authored andcommitted
refactor(log): refactoring log related code
1 parent 1a51195 commit 66615d0

15 files changed

+115
-238
lines changed

log/field_encoder.go

Lines changed: 16 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -79,14 +79,12 @@ func (enc *JSONEncoder) Reset() {
7979

8080
// AppendEncoderBegin writes the start of an encoder section, represented as a JSON object.
8181
func (enc *JSONEncoder) AppendEncoderBegin() {
82-
enc.last = jsonTokenObjectBegin
83-
enc.buf.WriteByte('{')
82+
enc.AppendObjectBegin()
8483
}
8584

8685
// AppendEncoderEnd writes the end of an encoder section (closes a JSON object).
8786
func (enc *JSONEncoder) AppendEncoderEnd() {
88-
enc.last = jsonTokenObjectEnd
89-
enc.buf.WriteByte('}')
87+
enc.AppendObjectEnd()
9088
}
9189

9290
// AppendObjectBegin starts a new JSON object.
@@ -114,24 +112,15 @@ func (enc *JSONEncoder) AppendArrayEnd() {
114112
}
115113

116114
// appendSeparator inserts a comma if necessary before a key or value.
117-
func (enc *JSONEncoder) appendSeparator(curr jsonToken) {
118-
switch curr {
119-
case jsonTokenKey:
120-
// Insert a comma between key-value pairs or elements
121-
if enc.last == jsonTokenObjectEnd || enc.last == jsonTokenArrayEnd || enc.last == jsonTokenValue {
122-
enc.buf.WriteByte(',')
123-
}
124-
case jsonTokenValue:
125-
if enc.last == jsonTokenValue {
126-
enc.buf.WriteByte(',')
127-
}
128-
default: // for linter
115+
func (enc *JSONEncoder) appendSeparator() {
116+
if enc.last == jsonTokenObjectEnd || enc.last == jsonTokenArrayEnd || enc.last == jsonTokenValue {
117+
enc.buf.WriteByte(',')
129118
}
130119
}
131120

132121
// AppendKey writes a JSON key (as a string followed by a colon).
133122
func (enc *JSONEncoder) AppendKey(key string) {
134-
enc.appendSeparator(jsonTokenKey)
123+
enc.appendSeparator()
135124
enc.last = jsonTokenKey
136125
enc.buf.WriteByte('"')
137126
enc.safeAddString(key)
@@ -141,35 +130,35 @@ func (enc *JSONEncoder) AppendKey(key string) {
141130

142131
// AppendBool writes a boolean value.
143132
func (enc *JSONEncoder) AppendBool(v bool) {
144-
enc.appendSeparator(jsonTokenValue)
133+
enc.appendSeparator()
145134
enc.last = jsonTokenValue
146135
enc.buf.WriteString(strconv.FormatBool(v))
147136
}
148137

149138
// AppendInt64 writes a signed 64-bit integer.
150139
func (enc *JSONEncoder) AppendInt64(v int64) {
151-
enc.appendSeparator(jsonTokenValue)
140+
enc.appendSeparator()
152141
enc.last = jsonTokenValue
153142
enc.buf.WriteString(strconv.FormatInt(v, 10))
154143
}
155144

156145
// AppendUint64 writes an unsigned 64-bit integer.
157146
func (enc *JSONEncoder) AppendUint64(u uint64) {
158-
enc.appendSeparator(jsonTokenValue)
147+
enc.appendSeparator()
159148
enc.last = jsonTokenValue
160149
enc.buf.WriteString(strconv.FormatUint(u, 10))
161150
}
162151

163152
// AppendFloat64 writes a floating-point number.
164153
func (enc *JSONEncoder) AppendFloat64(v float64) {
165-
enc.appendSeparator(jsonTokenValue)
154+
enc.appendSeparator()
166155
enc.last = jsonTokenValue
167156
enc.buf.WriteString(strconv.FormatFloat(v, 'f', -1, 64))
168157
}
169158

170159
// AppendString writes a string value (properly escaped).
171160
func (enc *JSONEncoder) AppendString(v string) {
172-
enc.appendSeparator(jsonTokenValue)
161+
enc.appendSeparator()
173162
enc.last = jsonTokenValue
174163
enc.buf.WriteByte('"')
175164
enc.safeAddString(v)
@@ -178,7 +167,7 @@ func (enc *JSONEncoder) AppendString(v string) {
178167

179168
// AppendReflect marshals any Go value into JSON and appends it.
180169
func (enc *JSONEncoder) AppendReflect(v interface{}) {
181-
enc.appendSeparator(jsonTokenValue)
170+
enc.appendSeparator()
182171
enc.last = jsonTokenValue
183172
b, err := json.Marshal(v)
184173
if err != nil {
@@ -257,7 +246,7 @@ type TextEncoder struct {
257246
separator string // Separator used between top-level key-value pairs
258247
jsonEncoder *JSONEncoder // Embedded JSON encoder for nested objects/arrays
259248
jsonDepth int8 // Tracks depth of nested JSON structures
260-
init bool // Tracks if the first key-value has been written
249+
firstField bool // Tracks if the first key-value has been written
261250
}
262251

263252
// NewTextEncoder creates a new TextEncoder writing to the given buffer, using the specified separator.
@@ -313,10 +302,11 @@ func (enc *TextEncoder) AppendKey(key string) {
313302
enc.jsonEncoder.AppendKey(key)
314303
return
315304
}
316-
if enc.init {
305+
if enc.firstField {
317306
enc.buf.WriteString(enc.separator)
307+
} else {
308+
enc.firstField = true
318309
}
319-
enc.init = true
320310
enc.buf.WriteString(key)
321311
enc.buf.WriteByte('=')
322312
}

log/field_encoder_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ func TestJSONEncoder(t *testing.T) {
106106
buf := bytes.NewBuffer(nil)
107107
enc := NewJSONEncoder(buf)
108108
enc.AppendEncoderBegin()
109-
writeFields(enc, testFields)
109+
WriteFields(enc, testFields)
110110
enc.AppendEncoderEnd()
111111
assert.ThatString(t, buf.String()).JsonEqual(`{
112112
"msg": "hello world\n\\\t\"\r",
@@ -254,7 +254,7 @@ func TestTextEncoder(t *testing.T) {
254254
buf := bytes.NewBuffer(nil)
255255
enc := NewTextEncoder(buf, "||")
256256
enc.AppendEncoderBegin()
257-
writeFields(enc, testFields)
257+
WriteFields(enc, testFields)
258258
{
259259
enc.AppendKey("object_2")
260260
enc.AppendObjectBegin()

log/field_value.go

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -239,19 +239,6 @@ func (v StringsValue) Encode(enc Encoder) {
239239
enc.AppendArrayEnd()
240240
}
241241

242-
// ObjectValue represents a slice of Field carried by Field.
243-
type ObjectValue []Field
244-
245-
// Encode encodes the data represented by v to an Encoder.
246-
func (v ObjectValue) Encode(enc Encoder) {
247-
enc.AppendObjectBegin()
248-
for _, f := range v {
249-
enc.AppendKey(f.Key)
250-
f.Val.Encode(enc)
251-
}
252-
enc.AppendObjectEnd()
253-
}
254-
255242
// ArrayValue represents a slice of Value carried by Field.
256243
type ArrayValue []Value
257244

@@ -263,3 +250,21 @@ func (v ArrayValue) Encode(enc Encoder) {
263250
}
264251
enc.AppendArrayEnd()
265252
}
253+
254+
// ObjectValue represents a slice of Field carried by Field.
255+
type ObjectValue []Field
256+
257+
// Encode encodes the data represented by v to an Encoder.
258+
func (v ObjectValue) Encode(enc Encoder) {
259+
enc.AppendObjectBegin()
260+
WriteFields(enc, v)
261+
enc.AppendObjectEnd()
262+
}
263+
264+
// WriteFields writes a slice of Field objects to the encoder.
265+
func WriteFields(enc Encoder, fields []Field) {
266+
for _, f := range fields {
267+
enc.AppendKey(f.Key)
268+
f.Val.Encode(enc)
269+
}
270+
}

log/log.go

Lines changed: 0 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,6 @@ import (
2323
"github.com/go-spring/spring-core/log/internal"
2424
)
2525

26-
// TagDefault is a default tag that can be used to set the default logger.
27-
var TagDefault = GetTag("_def")
28-
29-
// ctxDefault is the default context for formatted logging methods (e.g. Infof/Warnf).
30-
var ctxDefault = context.WithValue(context.Background(), "ctxDefault", "")
31-
3226
// TimeNow is a function that can be overridden to provide custom timestamp behavior (e.g., for testing).
3327
var TimeNow func(ctx context.Context) time.Time
3428

@@ -57,51 +51,26 @@ func Info(ctx context.Context, tag *Tag, fields ...Field) {
5751
Record(ctx, InfoLevel, tag, fields...)
5852
}
5953

60-
// Infof logs a formatted message at InfoLevel using the default tag.
61-
func Infof(format string, args ...interface{}) {
62-
Record(ctxDefault, InfoLevel, TagDefault, Msgf(format, args...))
63-
}
64-
6554
// Warn logs a message at WarnLevel using structured fields.
6655
func Warn(ctx context.Context, tag *Tag, fields ...Field) {
6756
Record(ctx, WarnLevel, tag, fields...)
6857
}
6958

70-
// Warnf logs a formatted message at WarnLevel using the default tag.
71-
func Warnf(format string, args ...interface{}) {
72-
Record(ctxDefault, WarnLevel, TagDefault, Msgf(format, args...))
73-
}
74-
7559
// Error logs a message at ErrorLevel using structured fields.
7660
func Error(ctx context.Context, tag *Tag, fields ...Field) {
7761
Record(ctx, ErrorLevel, tag, fields...)
7862
}
7963

80-
// Errorf logs a formatted message at ErrorLevel using the default tag.
81-
func Errorf(format string, args ...interface{}) {
82-
Record(ctxDefault, ErrorLevel, TagDefault, Msgf(format, args...))
83-
}
84-
8564
// Panic logs a message at PanicLevel using structured fields.
8665
func Panic(ctx context.Context, tag *Tag, fields ...Field) {
8766
Record(ctx, PanicLevel, tag, fields...)
8867
}
8968

90-
// Panicf logs a formatted message at PanicLevel using the default tag.
91-
func Panicf(format string, args ...interface{}) {
92-
Record(ctxDefault, PanicLevel, TagDefault, Msgf(format, args...))
93-
}
94-
9569
// Fatal logs a message at FatalLevel using structured fields.
9670
func Fatal(ctx context.Context, tag *Tag, fields ...Field) {
9771
Record(ctx, FatalLevel, tag, fields...)
9872
}
9973

100-
// Fatalf logs a formatted message at FatalLevel using the default tag.
101-
func Fatalf(format string, args ...interface{}) {
102-
Record(ctxDefault, FatalLevel, TagDefault, Msgf(format, args...))
103-
}
104-
10574
// Record is the core function that handles publishing log events.
10675
// It checks the logger level, captures caller information, gathers context fields,
10776
// and sends the log event to the logger.

log/log_level.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ import (
2121
"strings"
2222
)
2323

24+
func init() {
25+
RegisterConverter(ParseLevel)
26+
}
27+
2428
const (
2529
NoneLevel Level = iota // No logging
2630
TraceLevel // Very detailed logging, typically for debugging at a granular level

log/log_reader.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -70,14 +70,14 @@ func DumpNode(node *Node, indent int, buf *bytes.Buffer) {
7070
}
7171
buf.WriteString("}")
7272
}
73+
if node.Text != "" {
74+
buf.WriteString(" : ")
75+
buf.WriteString(node.Text)
76+
}
7377
for _, c := range node.Children {
7478
buf.WriteString("\n")
7579
DumpNode(c, indent+1, buf)
7680
}
77-
if node.Text != "" {
78-
buf.WriteString(" : ")
79-
buf.WriteString(strings.TrimSpace(node.Text))
80-
}
8181
}
8282

8383
// Reader is an interface for reading and parsing data into a Node structure.

log/log_refresh.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,9 @@ func RefreshReader(input io.Reader, ext string) error {
181181
}
182182
ss := strings.Split(base.Tags, ",")
183183
for _, s := range ss {
184+
if s = strings.TrimSpace(s); s == "" {
185+
return fmt.Errorf("RefreshReader: logger tag can not be empty")
186+
}
184187
cTags[s] = logger
185188
}
186189
}
@@ -215,7 +218,7 @@ func RefreshReader(input io.Reader, ext string) error {
215218
}
216219
}
217220

218-
for s, tag := range tags {
221+
for s, tag := range tagMap {
219222
logger := cRoot
220223
for i, r := range tagArray {
221224
if r.MatchString(s) {

log/log_tag.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import (
2020
"sync/atomic"
2121
)
2222

23-
var tags = map[string]*Tag{}
23+
var tagMap = map[string]*Tag{}
2424

2525
var initLogger = &Logger{
2626
privateConfig: &LoggerConfig{
@@ -71,11 +71,11 @@ func (m *Tag) SetLogger(logger *Logger) {
7171
// GetTag creates or retrieves a Tag by name.
7272
// If the tag does not exist, it is created and added to the global registry.
7373
func GetTag(tag string) *Tag {
74-
m, ok := tags[tag]
74+
m, ok := tagMap[tag]
7575
if !ok {
7676
m = &Tag{s: tag}
7777
m.v.Store(initLogger)
78-
tags[tag] = m
78+
tagMap[tag] = m
7979
}
8080
return m
8181
}

log/log_test.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
"github.com/lvan100/go-assert"
2626
)
2727

28+
var TagDefault = log.GetTag("_def")
2829
var TagRequestIn = log.GetTag("_com_request_in")
2930
var TagRequestOut = log.GetTag("_com_request_out")
3031

@@ -50,7 +51,7 @@ func TestLog(t *testing.T) {
5051
}
5152
})
5253

53-
log.Infof("hello %s", "world")
54+
log.Info(ctx, TagDefault, log.Msgf("hello %s", "world"))
5455
log.Info(ctx, TagRequestIn, log.Msgf("hello %s", "world"))
5556

5657
xml := `
@@ -89,6 +90,6 @@ func TestLog(t *testing.T) {
8990
}
9091
})
9192

92-
log.Infof("hello %s", "world")
93+
log.Info(ctx, TagDefault, log.Msgf("hello %s", "world"))
9394
log.Info(ctx, TagRequestIn, log.Msgf("hello %s", "world"))
9495
}

log/plugin.go

Lines changed: 4 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,6 @@ import (
2828

2929
var converters = map[reflect.Type]any{}
3030

31-
func init() {
32-
RegisterConverter(ParseLevel)
33-
}
34-
3531
// Converter function type that converts string to a specific type T.
3632
type Converter[T any] func(string) (T, error)
3733

@@ -41,11 +37,6 @@ func RegisterConverter[T any](fn Converter[T]) {
4137
converters[t] = fn
4238
}
4339

44-
// Initializer Optional initializer interface for plugin instances.
45-
type Initializer interface {
46-
Init() error
47-
}
48-
4940
// Lifecycle Optional lifecycle interface for plugin instances.
5041
type Lifecycle interface {
5142
Start() error
@@ -77,12 +68,12 @@ type Plugin struct {
7768
}
7869

7970
// RegisterPlugin Registers a plugin with a given name and type.
80-
func RegisterPlugin[T any](name string, typ PluginType) {
71+
func RegisterPlugin[T Lifecycle](name string, typ PluginType) {
8172
_, file, line, _ := runtime.Caller(1)
8273
if p, ok := plugins[name]; ok {
8374
panic(fmt.Errorf("duplicate plugin %s in %s:%d and %s:%d", typ, p.File, p.Line, file, line))
8475
}
85-
t := reflect.TypeFor[T]()
76+
t := reflect.TypeFor[T]().Elem()
8677
if t.Kind() != reflect.Struct {
8778
panic("T must be struct")
8879
}
@@ -98,16 +89,8 @@ func RegisterPlugin[T any](name string, typ PluginType) {
9889
// NewPlugin Creates and initializes a plugin instance.
9990
func NewPlugin(t reflect.Type, node *Node, properties map[string]string) (reflect.Value, error) {
10091
v := reflect.New(t)
101-
err := inject(v.Elem(), t, node, properties)
102-
if err != nil {
103-
err = errutil.WrapError(err, "create plugin %s error", t.String())
104-
return reflect.Value{}, err
105-
}
106-
if i, ok := v.Interface().(Initializer); ok {
107-
if err = i.Init(); err != nil {
108-
err = errutil.WrapError(err, "init plugin %s error", t.String())
109-
return reflect.Value{}, err
110-
}
92+
if err := inject(v.Elem(), t, node, properties); err != nil {
93+
return reflect.Value{}, errutil.WrapError(err, "create plugin %s error", t.String())
11194
}
11295
return v, nil
11396
}

0 commit comments

Comments
 (0)