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(promslog): add NewWithWriter() to allow logging other than stderr #686

Closed
wants to merge 1 commit into from
Closed
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
24 changes: 21 additions & 3 deletions promslog/slog.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,7 @@ type Config struct {
ioWriter io.Writer
}

// New returns a new slog.Logger. Each logged line will be annotated
// with a timestamp. The output always goes to stderr.
func New(config *Config) *slog.Logger {
func newSlogHandlerOptions(config *Config) *slog.HandlerOptions {
if config.Level == nil {
config.Level = &AllowedLevel{}
_ = config.Level.Set("info")
Expand All @@ -175,8 +173,28 @@ func New(config *Config) *slog.Logger {
logHandlerOpts.ReplaceAttr = goKitStyleReplaceAttrFunc
}

return logHandlerOpts
}

// New returns a new slog.Logger. Each logged line will be annotated
// with a timestamp. The output always goes to stderr.
func New(config *Config) *slog.Logger {
logHandlerOpts := newSlogHandlerOptions(config)
if config.Format != nil && config.Format.s == "json" {
return slog.New(slog.NewJSONHandler(config.ioWriter, logHandlerOpts))
}
return slog.New(slog.NewTextHandler(config.ioWriter, logHandlerOpts))
}

// New returns a new slog.Logger, with the logger's output set to the provided
// `io.Writer`. Management of the writer is beyond the scope of this function
// and is the responsibility of the caller to properly close, if needed. Each
// logged line will be annotated with a timestamp. The output always goes to
// stderr.
func NewWithWriter(config *Config, writer io.Writer) *slog.Logger {
logHandlerOpts := newSlogHandlerOptions(config)
if config.Format != nil && config.Format.s == "json" {
return slog.New(slog.NewJSONHandler(writer, logHandlerOpts))
}
return slog.New(slog.NewTextHandler(writer, logHandlerOpts))
}