diff --git a/funcr/funcr.go b/funcr/funcr.go index 121bf4d..8ecf434 100644 --- a/funcr/funcr.go +++ b/funcr/funcr.go @@ -94,6 +94,11 @@ type Options struct { // overhead, so some users might not want it. LogTimestamp bool + // TimestampFormat tells funcr how to render timestamps when LogTimestamp + // is enabled. If not specified, a default format will be used. For more + // details, see docs for Go's time.Layout. + TimestampFormat string + // Verbosity tells funcr which V logs to produce. Higher values enable // more logs. Info logs at or below this level will be written, while logs // above this level will be discarded. @@ -137,8 +142,6 @@ const ( Error ) -const timestampFmt = "2006-01-02 15:04:05.000000" - // fnlogger inherits some of its LogSink implementation from Formatter // and just needs to add some glue code. type fnlogger struct { @@ -190,7 +193,12 @@ func NewFormatterJSON(opts Options) Formatter { return newFormatter(opts, outputJSON) } +const defaultTimestampFmt = "2006-01-02 15:04:05.000000" + func newFormatter(opts Options, outfmt outputFormat) Formatter { + if opts.TimestampFormat == "" { + opts.TimestampFormat = defaultTimestampFmt + } f := Formatter{ outputFormat: outfmt, prefix: "", @@ -665,7 +673,7 @@ func (f Formatter) FormatInfo(level int, msg string, kvList []interface{}) (pref prefix = "" } if f.opts.LogTimestamp { - args = append(args, "ts", time.Now().Format(timestampFmt)) + args = append(args, "ts", time.Now().Format(f.opts.TimestampFormat)) } if policy := f.opts.LogCaller; policy == All || policy == Info { args = append(args, "caller", f.caller()) @@ -685,7 +693,7 @@ func (f Formatter) FormatError(err error, msg string, kvList []interface{}) (pre prefix = "" } if f.opts.LogTimestamp { - args = append(args, "ts", time.Now().Format(timestampFmt)) + args = append(args, "ts", time.Now().Format(f.opts.TimestampFormat)) } if policy := f.opts.LogCaller; policy == All || policy == Error { args = append(args, "caller", f.caller()) diff --git a/funcr/funcr_test.go b/funcr/funcr_test.go index a33a998..a6da5b6 100644 --- a/funcr/funcr_test.go +++ b/funcr/funcr_test.go @@ -1051,3 +1051,17 @@ func TestErrorWithCallDepth(t *testing.T) { } }) } + +func TestOptionsTimestampFormat(t *testing.T) { + cap := &capture{} + // This timestamp format contains none of the characters that are + // considered placeholders, so will produce a constant result. + sink := newSink(cap.Func, NewFormatter(Options{LogTimestamp: true, TimestampFormat: "TIMESTAMP"})) + dSink, _ := sink.(logr.CallDepthLogSink) + sink = dSink.WithCallDepth(1) + sink.Info(0, "msg") + expect := ` "ts"="TIMESTAMP" "level"=0 "msg"="msg"` + if cap.log != expect { + t.Errorf("\nexpected %q\n got %q", expect, cap.log) + } +}