Codebase list golang-github-go-logr-logr / 4d5bdde
funcr: Allow customization of the timestamp format Tim Hockin 2 years ago
2 changed file(s) with 26 addition(s) and 4 deletion(s). Raw diff Collapse all Expand all
9393 // overhead, so some users might not want it.
9494 LogTimestamp bool
9595
96 // TimestampFormat tells funcr how to render timestamps when LogTimestamp
97 // is enabled. If not specified, a default format will be used. For more
98 // details, see docs for Go's time.Layout.
99 TimestampFormat string
100
96101 // Verbosity tells funcr which V logs to produce. Higher values enable
97102 // more logs. Info logs at or below this level will be written, while logs
98103 // above this level will be discarded.
136141 Error
137142 )
138143
139 const timestampFmt = "2006-01-02 15:04:05.000000"
140
141144 // fnlogger inherits some of its LogSink implementation from Formatter
142145 // and just needs to add some glue code.
143146 type fnlogger struct {
189192 return newFormatter(opts, outputJSON)
190193 }
191194
195 const defaultTimestampFmt = "2006-01-02 15:04:05.000000"
196
192197 func newFormatter(opts Options, outfmt outputFormat) Formatter {
198 if opts.TimestampFormat == "" {
199 opts.TimestampFormat = defaultTimestampFmt
200 }
193201 f := Formatter{
194202 outputFormat: outfmt,
195203 prefix: "",
664672 prefix = ""
665673 }
666674 if f.opts.LogTimestamp {
667 args = append(args, "ts", time.Now().Format(timestampFmt))
675 args = append(args, "ts", time.Now().Format(f.opts.TimestampFormat))
668676 }
669677 if policy := f.opts.LogCaller; policy == All || policy == Info {
670678 args = append(args, "caller", f.caller())
684692 prefix = ""
685693 }
686694 if f.opts.LogTimestamp {
687 args = append(args, "ts", time.Now().Format(timestampFmt))
695 args = append(args, "ts", time.Now().Format(f.opts.TimestampFormat))
688696 }
689697 if policy := f.opts.LogCaller; policy == All || policy == Error {
690698 args = append(args, "caller", f.caller())
10501050 }
10511051 })
10521052 }
1053
1054 func TestOptionsTimestampFormat(t *testing.T) {
1055 cap := &capture{}
1056 // This timestamp format contains none of the characters that are
1057 // considered placeholders, so will produce a constant result.
1058 sink := newSink(cap.Func, NewFormatter(Options{LogTimestamp: true, TimestampFormat: "TIMESTAMP"}))
1059 dSink, _ := sink.(logr.CallDepthLogSink)
1060 sink = dSink.WithCallDepth(1)
1061 sink.Info(0, "msg")
1062 expect := ` "ts"="TIMESTAMP" "level"=0 "msg"="msg"`
1063 if cap.log != expect {
1064 t.Errorf("\nexpected %q\n got %q", expect, cap.log)
1065 }
1066 }