Skip to content

Commit

Permalink
Merge pull request #6 from cabify/add-default-factory
Browse files Browse the repository at this point in the history
Abstract Factory as interface
  • Loading branch information
joelmarty authored Jul 30, 2019
2 parents fbdfaec + 2e9d2a5 commit aca7d35
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 15 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Security
- Nothing

## [1.5.0] - 2019-07-30
### Added
- `LoggerFactory` interface abstracting `Factory` struct
- `DefaultFactory` global var that allows to replace factory used to generate loggers

## [1.4.0] - 2019-05-30
### Changed
- Baggage key is now a public string `"logctx-data-map-string-interface"` that can be set and read by anyone from any package.
Expand Down
17 changes: 17 additions & 0 deletions context_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,23 @@ func baggageString(b map[string]interface{}) string {
return strings.Join(kvPairs, ": ")
}

// Factory provides context aware loggers.
type Factory struct {
baseLogger Logger
}

// NewFactory instantiates a factory with the default logger.
func NewFactory() Factory {
return Factory{
baseLogger: DefaultLogger,
}
}

// For provides a logger which is aware of the passed context and will prepend the context baggage values.
func (f Factory) For(ctx context.Context) Logger {
return newBaggageLogger(ctx, f.baseLogger)
}

func newBaggageLogger(ctx context.Context, base Logger) baggageLogger {
return baggageLogger{
Logger: base,
Expand Down
21 changes: 6 additions & 15 deletions factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,16 @@ import (
"context"
)

// Factory provides context aware loggers.
type Factory struct {
baseLogger Logger
}

// NewFactory instantiates a factory with the default logger.
func NewFactory() Factory {
return Factory{
baseLogger: DefaultLogger,
}
}
// DefaultFactory is the factory used to create new loggers
var DefaultFactory Factory = NewFactory()

// For provides a logger which is aware of the passed context and will prepend the context baggage values.
func (f Factory) For(ctx context.Context) Logger {
return newBaggageLogger(ctx, f.baseLogger)
// LoggerFactory creates Logger instances
type LoggerFactory interface {
For(ctx context.Context) Logger
}

// For provides a logger which is aware of the passed context and will prepend
// the context baggage values, using DefaultLogger as base logger.
func For(ctx context.Context) Logger {
return newBaggageLogger(ctx, DefaultLogger)
return DefaultFactory.For(ctx)
}

0 comments on commit aca7d35

Please sign in to comment.