Skip to content

Commit

Permalink
feat: add WithRequestId and InfoContext methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Moranilt committed Feb 23, 2024
1 parent 9fe9bcf commit eb13196
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
22 changes: 13 additions & 9 deletions logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ type Logger interface {
Debug(msg string, args ...any)
Debugf(format string, args ...any)

InfoContext(ctx context.Context, msg string, args ...any)
Info(msg string, args ...any)
Infof(format string, args ...any)

Expand All @@ -83,6 +84,7 @@ type Logger interface {
WithRequestInfo(r *http.Request) Logger
WithField(key string, value any) Logger
WithFields(fields ...any) Logger
WithRequestId(ctx context.Context) Logger
}

func New(output io.Writer, t LoggerType) Logger {
Expand All @@ -109,6 +111,10 @@ func New(output io.Writer, t LoggerType) Logger {
return logger
}

func (s *SLogger) InfoContext(ctx context.Context, msg string, args ...any) {
s.root.Log(ctx, LevelInfo, msg, args...)
}

func (s *SLogger) Error(msg string, args ...any) {
s.root.Log(context.Background(), LevelError, msg, args...)
}
Expand Down Expand Up @@ -174,22 +180,20 @@ func (l *SLogger) Info(msg string, args ...any) {
}

func (l *SLogger) WithRequestInfo(r *http.Request) Logger {
l = l.WithRequestId(r.Context())
log := l.WithRequestId(r.Context())
var clientIP string

if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
clientIP = ip
}

return &SLogger{
root: l.root.With(
"path", r.URL.Path,
"method", r.Method,
"ip", clientIP,
),
}
return log.With(
"path", r.URL.Path,
"method", r.Method,
"ip", clientIP,
)
}
func (l *SLogger) WithRequestId(ctx context.Context) *SLogger {
func (l *SLogger) WithRequestId(ctx context.Context) Logger {
requestId := ctx.Value(CtxRequestId)
if requestId != "" {
return &SLogger{
Expand Down
6 changes: 6 additions & 0 deletions logger/mock_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,9 @@ func (m *MockLogger) WithField(key string, value any) Logger {
func (m *MockLogger) WithFields(fields ...any) Logger {
return m
}

func (m *MockLogger) WithRequestId(ctx context.Context) Logger {
return m
}

func (m *MockLogger) InfoContext(ctx context.Context, msg string, args ...any) {}

0 comments on commit eb13196

Please sign in to comment.