Skip to content

Commit

Permalink
Merge pull request #1141 from skrashevich/feat-log-terminal-check
Browse files Browse the repository at this point in the history
feat(logging): add interactive shell detection for console output
  • Loading branch information
AlexxIT authored May 28, 2024
2 parents 50ad3b2 + a6b9b49 commit 660979d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 18 deletions.
2 changes: 1 addition & 1 deletion internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ func Init() {
}

cfg.Mod = map[string]string{
"format": "color",
"format": "", // useless, but anyway
"level": "info",
"output": "stdout", // TODO: change to stderr someday
"time": zerolog.TimeFormatUnixMs,
Expand Down
44 changes: 27 additions & 17 deletions internal/app/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,21 @@ import (
"io"
"os"

"github.com/mattn/go-isatty"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)

var MemoryLog = newBuffer(16)

// NewLogger support:
// - output: empty (only to memory), stderr, stdout
// - format: empty (autodetect color support), color, json, text
// - time: empty (disable timestamp), UNIXMS, UNIXMICRO, UNIXNANO
// - level: disabled, trace, debug, info, warn, error...
func NewLogger(config map[string]string) zerolog.Logger {
var writer io.Writer

// support output only to memory
switch config["output"] {
case "stderr":
writer = os.Stderr
Expand All @@ -24,26 +29,31 @@ func NewLogger(config map[string]string) zerolog.Logger {
timeFormat := config["time"]

if writer != nil {
switch format := config["format"]; format {
case "color", "text":
if format := config["format"]; format != "json" {
console := &zerolog.ConsoleWriter{Out: writer}

switch format {
case "text":
console.NoColor = true
case "color":
console.NoColor = false // useless, but anyway
default:
// autodetection if output support color
// go-isatty - dependency for go-colorable - dependency for ConsoleWriter
console.NoColor = !isatty.IsTerminal(writer.(*os.File).Fd())
}

if timeFormat != "" {
writer = &zerolog.ConsoleWriter{
Out: writer,
NoColor: format == "text",
TimeFormat: "15:04:05.000",
}
console.TimeFormat = "15:04:05.000"
} else {
writer = &zerolog.ConsoleWriter{
Out: writer,
NoColor: format == "text",
PartsOrder: []string{
zerolog.LevelFieldName,
zerolog.CallerFieldName,
zerolog.MessageFieldName,
},
console.PartsOrder = []string{
zerolog.LevelFieldName,
zerolog.CallerFieldName,
zerolog.MessageFieldName,
}
}
case "json": // none

writer = console
}

writer = zerolog.MultiLevelWriter(writer, MemoryLog)
Expand Down

0 comments on commit 660979d

Please sign in to comment.