From 424554bc858fee8e7151b3454ee2531506815068 Mon Sep 17 00:00:00 2001 From: Nick Craig-Wood Date: Sat, 11 Apr 2020 18:02:50 +0100 Subject: [PATCH] fs: generalise machinery for putting extra values when using --use-json-log --- fs/accounting/stats.go | 2 +- fs/log.go | 29 +++++++++++++++++++++++++---- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/fs/accounting/stats.go b/fs/accounting/stats.go index 33bd690d2..0ed50a322 100644 --- a/fs/accounting/stats.go +++ b/fs/accounting/stats.go @@ -377,7 +377,7 @@ func (s *StatsInfo) Transferred() []TransferSnapshot { func (s *StatsInfo) Log() { if fs.Config.UseJSONLog { out, _ := s.RemoteStats() - fs.LogLevelPrintf(fs.Config.StatsLogLevel, nil, "%T\n", map[string]interface{}(out)) + fs.LogLevelPrintf(fs.Config.StatsLogLevel, nil, "%v%v\n", s, fs.LogValue("stats", out)) } else { fs.LogLevelPrintf(fs.Config.StatsLogLevel, nil, "%v\n", s) } diff --git a/fs/log.go b/fs/log.go index 785866e23..3baf00400 100644 --- a/fs/log.go +++ b/fs/log.go @@ -3,7 +3,6 @@ package fs import ( "fmt" "log" - "strings" "github.com/pkg/errors" "github.com/sirupsen/logrus" @@ -75,6 +74,27 @@ var LogPrint = func(level LogLevel, text string) { _ = log.Output(4, text) } +// LogValueItem describes keyed item for a JSON log entry +type LogValueItem struct { + key string + value interface{} +} + +// LogValue should be used as an argument to any logging calls to +// augment the JSON output with more structured information. +// +// key is the dictionary parameter used to store value. +func LogValue(key string, value interface{}) LogValueItem { + return LogValueItem{key: key, value: value} +} + +// String returns an empty string so LogValueItem entries won't show +// in the textual representation of logs. They need to be put in so +// the number of parameters of the log call matches. +func (j LogValueItem) String() string { + return "" +} + // LogPrintf produces a log string from the arguments passed in func LogPrintf(level LogLevel, o interface{}, text string, args ...interface{}) { out := fmt.Sprintf(text, args...) @@ -87,9 +107,10 @@ func LogPrintf(level LogLevel, o interface{}, text string, args ...interface{}) "objectType": fmt.Sprintf("%T", o), } } - if strings.HasPrefix(out, "map[") { - fields["json"] = args[0] - out = "" + for _, arg := range args { + if item, ok := arg.(LogValueItem); ok { + fields[item.key] = item.value + } } switch level { case LogLevelDebug: