Skip to content

Commit

Permalink
Add LOG_FORMATTER to select between text and json using env.
Browse files Browse the repository at this point in the history
  • Loading branch information
xlab committed Sep 28, 2022
1 parent 8d16d2b commit 92b70aa
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ NewLogger(wr io.Writer, formatter Formatter, hooks ...Hook) Logger
```

Available formatters:
* `suplog.JSONFormatter` — suplogs all log entries as JSON objects
* `suplog.TextFormatter` — suplogs log entries as text lines for TTY or without TTY colors.
* `suplog.TextFormatter` — suplogs log entries as text lines for TTY or without TTY colors (`LOG_FORMATTER=text`)
* `suplog.JSONFormatter` — suplogs all log entries as JSON objects (`LOG_FORMATTER=json`)

Available hooks:
* [github.com/xlab/suplog/hooks/debug](https://github.com/xlab/suplog/blob/master/hooks/debug/hook.go#L14)
Expand Down
20 changes: 17 additions & 3 deletions suplog.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,16 @@ import (
"github.com/xlab/suplog/stackcache"
)

// NewLogger constructs a new suplogger.
// NewLogger constructs a new suplogger. The default formatter would be TextFormatter
// if not overrident by and env variable.
func NewLogger(wr io.Writer, formatter Formatter, hooks ...Hook) Logger {
if formatter == nil {
formatter = new(TextFormatter)
switch os.Getenv("LOG_FORMATTER") {
case "json":
formatter = new(JSONFormatter)
default:
formatter = new(TextFormatter)
}
}

log := &suplogger{
Expand Down Expand Up @@ -70,10 +76,18 @@ func (l *suplogger) initOnce() {
l.writer = os.Stderr
}

var formatter Formatter
switch os.Getenv("LOG_FORMATTER") {
case "json":
formatter = new(JSONFormatter)
default:
formatter = new(TextFormatter)
}

// otherwise init output with conservative defaults
l.logger = &logrus.Logger{
Out: l.writer,
Formatter: new(TextFormatter),
Formatter: formatter,
Hooks: make(LevelHooks),
Level: DebugLevel,
ExitFunc: closer.Exit,
Expand Down

0 comments on commit 92b70aa

Please sign in to comment.