Skip to content

Commit

Permalink
log/stdlog: allow to pass options when creating a sublogger
Browse files Browse the repository at this point in the history
  • Loading branch information
budziam authored and mmatczuk committed Sep 17, 2024
1 parent a74f6d8 commit 10de653
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
9 changes: 9 additions & 0 deletions log/stdlog/opts.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,22 @@

package stdlog

import flog "github.com/saucelabs/forwarder/log"

// WithLabels allows to set labels that are added to each log message.
func WithLabels(labels ...string) Option {
return func(l *Logger) {
l.labels = labels
}
}

// WithLevel allows to set the logging level.
func WithLevel(level flog.Level) Option {
return func(l *Logger) {
l.level = level
}
}

// WithDecorate allows to a function that modifies the log message before it is written.
func WithDecorate(f func(string) string) Option {
return func(l *Logger) {
Expand Down
6 changes: 5 additions & 1 deletion log/stdlog/stdlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,17 @@ type Logger struct {
onError func(name string)
}

func (sl Logger) Named(name string) *Logger { //nolint:gocritic // we pass by value to get a copy
func (sl Logger) Named(name string, opts ...Option) *Logger { //nolint:gocritic // we pass by value to get a copy
sl.name = name

sl.errorPfx = logLinePrefix(sl.labels, name, "ERROR")
sl.infoPfx = logLinePrefix(sl.labels, name, "INFO")
sl.debugPfx = logLinePrefix(sl.labels, name, "DEBUG")

for _, opt := range opts {
opt(&sl)
}

return &sl
}

Expand Down
20 changes: 20 additions & 0 deletions log/stdlog/stdlog_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright 2022-2024 Sauce Labs Inc., all rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

package stdlog

import (
"testing"

flog "github.com/saucelabs/forwarder/log"
"github.com/stretchr/testify/assert"
)

func TestLoggerNamedAllowsToPassCustomLevel(t *testing.T) {
l := New(flog.DefaultConfig())
f := l.Named("foo", WithLevel(0))
assert.Equal(t, flog.Level(0), f.level)
}

0 comments on commit 10de653

Please sign in to comment.