-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Add slog hook #1407
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
Open
flimzy
wants to merge
5
commits into
sirupsen:master
Choose a base branch
from
flimzy:slog
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+245
−0
Open
Add slog hook #1407
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
02d2861
Basic slog hook
flimzy 16dd42a
Allow for custom level mapping between logrus and slog
flimzy 1a23b10
Propagate Handle() errors to Fire()'s caller
flimzy bc46ba0
Test that we report the proper caller
flimzy 9d947b7
Optimizations and improvements from PR feedback
flimzy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| //go:build go1.21 | ||
| // +build go1.21 | ||
|
|
||
| package slog | ||
|
|
||
| import ( | ||
| "log/slog" | ||
|
|
||
| "github.com/sirupsen/logrus" | ||
| ) | ||
|
|
||
| // LevelMapper maps a [github.com/sirupsen/logrus.Level] value to a | ||
| // [slog.Leveler] value. To change the default level mapping, for instance | ||
| // to allow mapping to custom or dynamic slog levels in your application, set | ||
| // [SlogHook.LevelMapper] to your own implementation of this function. | ||
| type LevelMapper func(logrus.Level) slog.Leveler | ||
|
|
||
| // SlogHook sends logs to slog. | ||
| type SlogHook struct { | ||
| logger *slog.Logger | ||
| LevelMapper LevelMapper | ||
| } | ||
|
|
||
| var _ logrus.Hook = (*SlogHook)(nil) | ||
|
|
||
| // NewSlogHook creates a hook that sends logs to an existing slog Logger. | ||
| // This hook is intended to be used during transition from Logrus to slog, | ||
| // or as a shim between different parts of your application or different | ||
| // libraries that depend on different loggers. | ||
| // | ||
| // Example usage: | ||
| // | ||
| // logger := slog.New(slog.NewJSONHandler(os.Stderr, nil)) | ||
| // hook := NewSlogHook(logger) | ||
| func NewSlogHook(logger *slog.Logger) *SlogHook { | ||
| return &SlogHook{ | ||
| logger: logger, | ||
| } | ||
| } | ||
|
|
||
| func (h *SlogHook) toSlogLevel(level logrus.Level) slog.Leveler { | ||
| if h.LevelMapper != nil { | ||
| return h.LevelMapper(level) | ||
| } | ||
| switch level { | ||
| case logrus.PanicLevel, logrus.FatalLevel, logrus.ErrorLevel: | ||
| return slog.LevelError | ||
| case logrus.WarnLevel: | ||
| return slog.LevelWarn | ||
| case logrus.InfoLevel: | ||
| return slog.LevelInfo | ||
| case logrus.DebugLevel, logrus.TraceLevel: | ||
| return slog.LevelDebug | ||
| default: | ||
| // Treat all unknown levels as errors | ||
| return slog.LevelError | ||
| } | ||
| } | ||
|
|
||
| // Levels always returns all levels, since slog allows controlling level | ||
| // enabling based on context. | ||
| func (h *SlogHook) Levels() []logrus.Level { | ||
| return logrus.AllLevels | ||
| } | ||
|
|
||
| // Fire sends entry to the underlying slog logger. The Time and Caller fields | ||
| // of entry are ignored. | ||
| func (h *SlogHook) Fire(entry *logrus.Entry) error { | ||
flimzy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| lvl := h.toSlogLevel(entry.Level).Level() | ||
| if !h.logger.Handler().Enabled(entry.Context, lvl) { | ||
| return nil | ||
| } | ||
| attrs := make([]any, 0, len(entry.Data)) | ||
| for k, v := range entry.Data { | ||
| attrs = append(attrs, slog.Any(k, v)) | ||
| } | ||
| var pc uintptr | ||
| if entry.Caller != nil { | ||
| pc = entry.Caller.PC | ||
| } | ||
| r := slog.NewRecord(entry.Time, lvl, entry.Message, pc) | ||
| r.Add(attrs...) | ||
| return h.logger.Handler().Handle(entry.Context, r) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,161 @@ | ||
| //go:build go1.21 | ||
| // +build go1.21 | ||
|
|
||
| package slog | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "errors" | ||
| "io" | ||
| "log/slog" | ||
| "os" | ||
| "regexp" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/sirupsen/logrus" | ||
| ) | ||
|
|
||
| func TestSlogHook(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| mapper LevelMapper | ||
| fn func(*logrus.Logger) | ||
| want []string | ||
| }{ | ||
| { | ||
| name: "defaults", | ||
| fn: func(log *logrus.Logger) { | ||
| log.Info("info") | ||
| }, | ||
| want: []string{ | ||
| "level=INFO msg=info", | ||
| }, | ||
| }, | ||
| { | ||
| name: "with fields", | ||
| fn: func(log *logrus.Logger) { | ||
| log.WithFields(logrus.Fields{ | ||
| "chicken": "cluck", | ||
| }).Error("error") | ||
| }, | ||
| want: []string{ | ||
| "level=ERROR msg=error chicken=cluck", | ||
| }, | ||
| }, | ||
| { | ||
| name: "level mapper", | ||
| mapper: func(logrus.Level) slog.Leveler { | ||
| return slog.LevelInfo | ||
| }, | ||
| fn: func(log *logrus.Logger) { | ||
| log.WithFields(logrus.Fields{ | ||
| "chicken": "cluck", | ||
| }).Error("error") | ||
| }, | ||
| want: []string{ | ||
| "level=INFO msg=error chicken=cluck", | ||
| }, | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| buf := &bytes.Buffer{} | ||
| slogLogger := slog.New(slog.NewTextHandler(buf, &slog.HandlerOptions{ | ||
| // Remove timestamps from logs, for easier comparison | ||
| ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr { | ||
| if a.Key == slog.TimeKey { | ||
| return slog.Attr{} | ||
| } | ||
| return a | ||
| }, | ||
| })) | ||
| log := logrus.New() | ||
| log.Out = io.Discard | ||
| hook := NewSlogHook(slogLogger) | ||
| hook.LevelMapper = tt.mapper | ||
| log.AddHook(hook) | ||
| tt.fn(log) | ||
| got := strings.Split(strings.TrimSpace(buf.String()), "\n") | ||
| if len(got) != len(tt.want) { | ||
| t.Errorf("Got %d log lines, expected %d", len(got), len(tt.want)) | ||
| return | ||
| } | ||
| for i, line := range got { | ||
| if line != tt.want[i] { | ||
| t.Errorf("line %d differs from expectation.\n Got: %s\nWant: %s", i, line, tt.want[i]) | ||
| } | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| type errorHandler struct{} | ||
|
|
||
| var _ slog.Handler = (*errorHandler)(nil) | ||
|
|
||
| func (h *errorHandler) Enabled(context.Context, slog.Level) bool { | ||
| return true | ||
| } | ||
|
|
||
| func (h *errorHandler) Handle(context.Context, slog.Record) error { | ||
| return errors.New("boom") | ||
| } | ||
|
|
||
| func (h *errorHandler) WithAttrs([]slog.Attr) slog.Handler { | ||
| return h | ||
| } | ||
|
|
||
| func (h *errorHandler) WithGroup(string) slog.Handler { | ||
| return h | ||
| } | ||
|
|
||
| func TestSlogHook_error_propagates(t *testing.T) { | ||
| stderr := os.Stderr | ||
| r, w, err := os.Pipe() | ||
| if err != nil { | ||
| t.Fatalf("failed to create pipe: %v", err) | ||
| } | ||
| os.Stderr = w | ||
| t.Cleanup(func() { | ||
| os.Stderr = stderr | ||
| _ = r.Close() | ||
| _ = w.Close() | ||
| }) | ||
|
|
||
| slogLogger := slog.New(&errorHandler{}) | ||
| log := logrus.New() | ||
| log.Out = io.Discard | ||
| log.AddHook(NewSlogHook(slogLogger)) | ||
| log.WithField("key", "value").Error("test error") | ||
| _ = w.Close() | ||
| gotStderr, _ := io.ReadAll(r) | ||
| if !bytes.Contains(gotStderr, []byte("boom")) { | ||
| t.Errorf("expected stderr to contain 'boom', got: %s", string(gotStderr)) | ||
| } | ||
| } | ||
|
|
||
| func TestSlogHook_source(t *testing.T) { | ||
| buf := &bytes.Buffer{} | ||
| slogLogger := slog.New(slog.NewTextHandler(buf, &slog.HandlerOptions{ | ||
| ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr { | ||
| if a.Key == slog.TimeKey { | ||
| return slog.Attr{} | ||
| } | ||
| return a | ||
| }, | ||
| AddSource: true, | ||
| })) | ||
| log := logrus.New() | ||
| log.Out = io.Discard | ||
| log.ReportCaller = true | ||
| log.AddHook(NewSlogHook(slogLogger)) | ||
| log.Info("info with source") | ||
| got := strings.TrimSpace(buf.String()) | ||
| wantRE := regexp.MustCompile(`source=.*hooks/slog/slog_test\.go:\d+`) | ||
| if !wantRE.MatchString(got) { | ||
| t.Errorf("expected log to contain source attribute matching %q, got: %s", wantRE.String(), got) | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.