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

fix slog logger constructor nil pointer bug #296

Merged
merged 2 commits into from
Jul 23, 2024
Merged
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
42 changes: 31 additions & 11 deletions logging/slog_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,32 @@ type SLoggerOptions struct {
NoColor bool
}

// default SLogger options are used when no options are provided
// they are the development options (debug logs with source)
var defaultTintOptions = tint.Options{
AddSource: false,
Level: slog.LevelInfo,
ReplaceAttr: nil,
TimeFormat: time.StampMilli,
NoColor: false,
}

// NewSlogTextLogger creates a new SLogger with a text handler
// Default behavior is colored log outputs. To disable colors, set opts.NoColor to true.
func NewTextSLogger(outputWriter io.Writer, opts *SLoggerOptions) *SLogger {
tintOptions := &tint.Options{
AddSource: opts.AddSource,
Level: opts.Level,
ReplaceAttr: opts.ReplaceAttr,
TimeFormat: opts.TimeFormat,
NoColor: opts.NoColor,
var tintOptions tint.Options
if opts == nil {
tintOptions = defaultTintOptions
} else {
tintOptions = tint.Options{
AddSource: opts.AddSource,
shrimalmadhur marked this conversation as resolved.
Show resolved Hide resolved
Level: opts.Level,
ReplaceAttr: opts.ReplaceAttr,
TimeFormat: opts.TimeFormat,
NoColor: opts.NoColor,
}
}
handler := tint.NewHandler(outputWriter, tintOptions)
handler := tint.NewHandler(outputWriter, &tintOptions)
logger := slog.New(handler)
return &SLogger{
logger,
Expand All @@ -63,10 +78,15 @@ func NewTextSLogger(outputWriter io.Writer, opts *SLoggerOptions) *SLogger {
// Currently colors are not supported with json handler. If colors are required,
// use NewTextSLogger instead.
func NewJsonSLogger(outputWriter io.Writer, opts *SLoggerOptions) *SLogger {
handlerOpts := &slog.HandlerOptions{
AddSource: opts.AddSource,
Level: opts.Level,
ReplaceAttr: opts.ReplaceAttr,
var handlerOpts *slog.HandlerOptions
if opts == nil {
handlerOpts = &slog.HandlerOptions{}
} else {
handlerOpts = &slog.HandlerOptions{
AddSource: opts.AddSource,
Level: opts.Level,
ReplaceAttr: opts.ReplaceAttr,
}
}
handler := slog.NewJSONHandler(outputWriter, handlerOpts)
logger := slog.New(handler)
Expand Down