Skip to content

Commit

Permalink
Merge pull request #126 from hashicorp/f-sublogger-hook
Browse files Browse the repository at this point in the history
Add ability to wrap new subloggers
  • Loading branch information
evanphx committed Mar 20, 2023
2 parents d0286ec + f7ba5ae commit b4bfc9a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
17 changes: 14 additions & 3 deletions intlogger.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ type intLogger struct {

// create subloggers with their own level setting
independentLevels bool

subloggerHook func(sub Logger) Logger
}

// New returns a configured logger.
Expand Down Expand Up @@ -151,6 +153,7 @@ func newLogger(opts *LoggerOptions) *intLogger {
independentLevels: opts.IndependentLevels,
headerColor: headerColor,
fieldColor: fieldColor,
subloggerHook: opts.SubloggerHook,
}
if opts.IncludeLocation {
l.callerOffset = offsetIntLogger + opts.AdditionalLocationOffset
Expand All @@ -166,13 +169,21 @@ func newLogger(opts *LoggerOptions) *intLogger {
l.timeFormat = opts.TimeFormat
}

if l.subloggerHook == nil {
l.subloggerHook = identityHook
}

l.setColorization(opts)

atomic.StoreInt32(l.level, int32(level))

return l
}

func identityHook(logger Logger) Logger {
return logger
}

// offsetIntLogger is the stack frame offset in the call stack for the caller to
// one of the Warn, Info, Log, etc methods.
const offsetIntLogger = 3
Expand Down Expand Up @@ -774,7 +785,7 @@ func (l *intLogger) With(args ...interface{}) Logger {
sl.implied = append(sl.implied, MissingKey, extra)
}

return sl
return l.subloggerHook(sl)
}

// Create a new sub-Logger that a name decending from the current name.
Expand All @@ -788,7 +799,7 @@ func (l *intLogger) Named(name string) Logger {
sl.name = name
}

return sl
return l.subloggerHook(sl)
}

// Create a new sub-Logger with an explicit name. This ignores the current
Expand All @@ -799,7 +810,7 @@ func (l *intLogger) ResetNamed(name string) Logger {

sl.name = name

return sl
return l.subloggerHook(sl)
}

func (l *intLogger) ResetOutput(opts *LoggerOptions) error {
Expand Down
7 changes: 7 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,13 @@ type LoggerOptions struct {
// logger will not affect any subloggers, and SetLevel on any subloggers
// will not affect the parent or sibling loggers.
IndependentLevels bool

// SubloggerHook registers a function that is called when a sublogger via
// Named, With, or ResetNamed is created. If defined, the function is passed
// the newly created Logger and the returned Logger is returned from the
// original function. This option allows customization via interception and
// wrapping of Logger instances.
SubloggerHook func(sub Logger) Logger
}

// InterceptLogger describes the interface for using a logger
Expand Down

0 comments on commit b4bfc9a

Please sign in to comment.