Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add —log-timestamps option #1025

Merged
merged 6 commits into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions internal/log/configure.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ import (

// Config for the logger.
type Config struct {
Level Level `help:"Log level." default:"info" env:"LOG_LEVEL"`
JSON bool `help:"Log in JSON format." env:"LOG_JSON"`
Level Level `help:"Log level." default:"info" env:"LOG_LEVEL"`
JSON bool `help:"Log in JSON format." env:"LOG_JSON"`
Timestamps bool `help:"Include timestamps in text logs." env:"LOG_TIMESTAMPS"`
}

// Configure returns a new logger based on the config.
Expand All @@ -16,7 +17,7 @@ func Configure(w io.Writer, cfg Config) *Logger {
if cfg.JSON {
sink = newJSONSink(w)
} else {
sink = newPlainSink(w)
sink = newPlainSink(w, cfg.Timestamps)
}
return New(cfg.Level, sink)
}
26 changes: 19 additions & 7 deletions internal/log/plain.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"io"
"os"
"time"

"github.com/mattn/go-isatty"
)
Expand All @@ -18,31 +19,42 @@ var colours = map[Level]string{

var _ Sink = (*plainSink)(nil)

func newPlainSink(w io.Writer) *plainSink {
func newPlainSink(w io.Writer, logTime bool) *plainSink {
var isaTTY bool
if f, ok := w.(*os.File); ok {
isaTTY = isatty.IsTerminal(f.Fd())
}
return &plainSink{
isaTTY: isaTTY,
w: w,
isaTTY: isaTTY,
w: w,
logTime: logTime,
}
}

type plainSink struct {
isaTTY bool
w io.Writer
isaTTY bool
w io.Writer
logTime bool
}

// Log implements Sink
func (t *plainSink) Log(entry Entry) error {
var prefix string

// Add timestamp if required
if t.logTime {
prefix += entry.Time.Format(time.TimeOnly) + " "
}

// Add scope if required
scope, exists := entry.Attributes[scopeKey]
if exists {
prefix = entry.Level.String() + ":" + scope + ": "
prefix += entry.Level.String() + ":" + scope + ": "
} else {
prefix = entry.Level.String() + ": "
prefix += entry.Level.String() + ": "
}

// Print
var err error
if t.isaTTY {
_, err = fmt.Fprintf(t.w, "%s%s%s\x1b[0m\n", colours[entry.Level], prefix, entry.Message)
Expand Down