Skip to content

Commit

Permalink
feat: add —log-timestamps option (#1025)
Browse files Browse the repository at this point in the history
#1009
Adding `add --log-timestamps` include timestamps in terminal logs

Example
```
16:26:20 info: Starting FTL with 1 controller(s) and 0 runner(s)
16:26:20 warn: Detected change in +/Users/mtoohey/Code/ftl/examples/go/echo/go.sum, rebuilding...
16:26:20 error: Error deploying module /Users/mtoohey/Code/ftl/examples/go/echo. Will retry: module "time" not found
16:26:20 warn: Detected change in +/Users/mtoohey/Code/ftl/examples/go/time/time.go, rebuilding...
16:26:20 info:time: Building module
```
  • Loading branch information
matt2e authored Mar 6, 2024
1 parent 714fe0c commit 1a713ef
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 10 deletions.
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

0 comments on commit 1a713ef

Please sign in to comment.