Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add WithRequestId and InfoContext methods #7

Merged
merged 1 commit into from
Feb 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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) {}
Loading