Skip to content

Commit

Permalink
Merge pull request #42 from sunist-c/main
Browse files Browse the repository at this point in the history
fix(logger): 减少 uuid 的长度,解决 attach fields 的错误实现
  • Loading branch information
sunist-c authored Nov 11, 2024
2 parents 8dbdc7d + a6f144f commit 6fce560
Show file tree
Hide file tree
Showing 5 changed files with 66 additions and 34 deletions.
23 changes: 18 additions & 5 deletions logger/custom.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,23 @@ import (
)

const (
serviceEnvKey = "AC_SERVICE"
extraFieldsKey = "AC_EXTRA_FIELDS"
serviceEnvKey = "AC_SERVICE"
extraFieldsKey = "AC_EXTRA_FIELDS"
pkgDirectoryKey = "AC_PKG_DIR"
)

var (
serviceEnv string
extraFields string
pkgDirectory string
)

func init() {
serviceEnv = os.Getenv(serviceEnvKey)
extraFields = os.Getenv(extraFieldsKey)
pkgDirectory = os.Getenv(pkgDirectoryKey)
}

// NewCustomLoggerWithOpts creates and returns a new custom logger instance
// with the specified options. This function initializes a custom logger
// with default values and then applies the provided options to it.
Expand Down Expand Up @@ -43,12 +56,12 @@ func NewCustomLoggerWithOpts(opts ...Option) Logger {

// Inject service field
attachField := NewFields()
if srv := os.Getenv(serviceEnvKey); srv != "" {
attachField = attachField.WithService(srv)
if serviceEnv != "" {
attachField = attachField.WithService(serviceEnv)
}

// Inject extra fields
if extraKeys := strings.Split(strings.TrimSpace(os.Getenv(extraFieldsKey)), ","); len(extraKeys) > 0 {
if extraKeys := strings.Split(strings.TrimSpace(extraFields), ","); len(extraKeys) > 0 {
for _, key := range extraKeys {
if value := os.Getenv(key); value != "" {
attachField = attachField.WithField(key, value)
Expand Down
61 changes: 37 additions & 24 deletions logger/fields.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package logger

import (
"context"
"os"
"strings"
"time"

"github.com/alioth-center/infrastructure/trace"
Expand All @@ -25,28 +25,20 @@ func (l Level) shouldLog(level Level) bool {
}

var (
workingDirectory = "./"
timeFormat = "2006.01.02-15:04:05.000Z07:00"
LevelValueMap = map[Level]int{LevelDebug: 0, LevelInfo: 1, LevelWarn: 2, LevelError: 3, LevelFatal: 4, LevelPanic: 5}
timeFormat = "2006.01.02-15:04:05.000Z07:00"
LevelValueMap = map[Level]int{LevelDebug: 0, LevelInfo: 1, LevelWarn: 2, LevelError: 3, LevelFatal: 4, LevelPanic: 5}
)

func init() {
wd, getWdErr := os.Getwd()
if getWdErr == nil {
workingDirectory = wd
}
}

type Entry struct {
ctx context.Context `json:"-" yaml:"-" xml:"-"`
File string `json:"file" yaml:"file" xml:"file"`
Level string `json:"level" yaml:"level" xml:"level"`
Service string `json:"service" yaml:"service" xml:"service"`
TraceID string `json:"trace_id" yaml:"trace_id" xml:"trace_id"`
CallTime string `json:"call_time" yaml:"call_time" xml:"call_time"`
Data any `json:"data,omitempty" yaml:"data,omitempty" xml:"data,omitempty"`
Extra map[string]any `json:"extra,omitempty" yaml:"extra,omitempty" xml:"extra,omitempty"`
Message string `json:"message,omitempty" yaml:"message,omitempty" xml:"message,omitempty"`
ctx context.Context
File string `json:"file" yaml:"file" xml:"file"`
Level string `json:"level" yaml:"level" xml:"level"`
Service string `json:"service" yaml:"service" xml:"service"`
TraceID string `json:"trace_id" yaml:"trace_id" xml:"trace_id"`
CallTime string `json:"call_time" yaml:"call_time" xml:"call_time"`
Data any `json:"data,omitempty" yaml:"data,omitempty" xml:"data,omitempty"`
Extra map[string]any `json:"extra,omitempty" yaml:"extra,omitempty" xml:"extra,omitempty"`
Message string `json:"message,omitempty" yaml:"message,omitempty" xml:"message,omitempty"`
}

type Fields interface {
Expand Down Expand Up @@ -78,9 +70,26 @@ type fields struct {
func (f *fields) init(ctx context.Context) Fields {
f.file, f.ctx, f.level = trace.Caller(1), trace.FromContext(ctx), LevelInfo

f.trimFile()
return f
}

func (f *fields) trimFile() {
// pkgDirectory = /go/pkg/mod/
// file = /go/pkg/mod/github.com/alioth-center/[email protected]/thirdparty/openai/client.go:185
// result = github.com/alioth-center/infrastructure /thirdparty/openai/client.go:185

if pkgDirectory != "" {
f.file = strings.TrimPrefix(f.file, pkgDirectory)
}

if atIndex := strings.Index(f.file, "@"); atIndex != -1 {
if slashIndex := strings.Index(f.file[atIndex:], "/"); slashIndex != -1 {
f.file = f.file[:atIndex] + f.file[atIndex+slashIndex:]
}
}
}

// Export 导出日志字段
func (f *fields) Export() *Entry {
traceID, ctx := trace.TransformContext(f.ctx)
Expand Down Expand Up @@ -165,21 +174,25 @@ func (f *fields) WithBaseFields(base Fields) Fields {

func (f *fields) WithAttachFields(attach Fields) Fields {
entry := attach.Export()
if entry.Level != "" {

if entry.Level != "" && f.level == "" {
f.level = Level(entry.Level)
}
if entry.Service != "" {

if entry.Service != "" && f.service == "" {
f.service = entry.Service
}
if entry.Message != "" {
if entry.Message != "" && f.message == "" {
f.message = entry.Message
}
if entry.Data != nil {
if entry.Data != nil && f.data == nil {
f.data = entry.Data
}

if f.extra == nil {
f.extra = map[string]any{}
}

for k, v := range entry.Extra {
f.extra[k] = v
}
Expand Down
2 changes: 1 addition & 1 deletion logger/unit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,5 @@ func TestFields(t *testing.T) {
os.Setenv(extraFieldsKey, "KEY1,KEY2")
os.Setenv("KEY1", "VALUE1")
os.Setenv("KEY2", "VALUE2")
NewCustomLoggerWithOpts().Info(NewFields().WithMessage("test"))
NewCustomLoggerWithOpts().Error(NewFields().WithMessage("test"))
}
9 changes: 5 additions & 4 deletions trace/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import (
"context"
"net"

"github.com/google/uuid"
"github.com/alioth-center/infrastructure/utils/generate"

"google.golang.org/grpc/peer"
)

Expand Down Expand Up @@ -63,7 +64,7 @@ func FromContext(ctx context.Context) (traced context.Context) {
return ctx
}

return context.WithValue(ctx, traceIDKey, uuid.NewString()) // nolint
return context.WithValue(ctx, traceIDKey, generate.TraceID()) // nolint
}

// ForkContext creates a new traced context from an existing context, copying only the trace ID.
Expand Down Expand Up @@ -103,7 +104,7 @@ func ForkContextWithOpts(ctx context.Context, fields ...string) (forked context.

// NewContext creates a new context with a generated trace ID.
func NewContext() context.Context {
return NewContextWithTid(uuid.NewString())
return NewContextWithTid(generate.TraceID())
}

// NewContextWithTid creates a new context with the specified trace ID.
Expand All @@ -113,7 +114,7 @@ func NewContextWithTid(traceID string) context.Context {

// AttachTraceID attaches a newly generated trace ID to the given context, returning the new trace ID and the updated context.
func AttachTraceID(ctx context.Context) (traceID string, result context.Context) {
traceID = uuid.NewString()
traceID = generate.TraceID()
return traceID, context.WithValue(ctx, traceIDKey, traceID) // nolint
}

Expand Down
5 changes: 5 additions & 0 deletions utils/generate/random.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,8 @@ func RandomFourDigitNumberCodeWithPrefix(prefix string) string {
func UUID() string {
return uuid.NewString()
}

// TraceID 生成TraceID
func TraceID() string {
return strings.ReplaceAll(UUID(), "-", "")
}

0 comments on commit 6fce560

Please sign in to comment.