github.com/observiq/carbon@v0.9.11-0.20200820160507-1b872e368a5e/commands/logging.go (about) 1 package commands 2 3 import ( 4 "net/url" 5 "os" 6 "path/filepath" 7 "runtime" 8 "sync" 9 10 "go.uber.org/zap" 11 "go.uber.org/zap/zapcore" 12 ) 13 14 func init() { 15 registerWindowsSink() 16 } 17 18 func newDefaultLoggerAt(level zapcore.Level, path string) *zap.SugaredLogger { 19 logCfg := zap.NewProductionConfig() 20 logCfg.Level = zap.NewAtomicLevelAt(level) 21 logCfg.Sampling.Initial = 5 22 logCfg.Sampling.Thereafter = 100 23 logCfg.EncoderConfig.CallerKey = "" 24 logCfg.EncoderConfig.StacktraceKey = "" 25 logCfg.EncoderConfig.TimeKey = "timestamp" 26 logCfg.EncoderConfig.MessageKey = "message" 27 logCfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder 28 29 if path != "" { 30 logCfg.OutputPaths = []string{pathToURI(path)} 31 } 32 33 baseLogger, err := logCfg.Build() 34 if err != nil { 35 panic(err) 36 } 37 return baseLogger.Sugar() 38 } 39 40 func pathToURI(path string) string { 41 switch runtime.GOOS { 42 case "windows": 43 return "winfile:///" + filepath.ToSlash(path) 44 default: 45 return filepath.ToSlash(path) 46 } 47 } 48 49 var registerSyncsOnce sync.Once 50 51 func registerWindowsSink() { 52 registerSyncsOnce.Do(func() { 53 if runtime.GOOS == "windows" { 54 err := zap.RegisterSink("winfile", newWinFileSink) 55 if err != nil { 56 panic(err) 57 } 58 } 59 }) 60 } 61 62 func newWinFileSink(u *url.URL) (zap.Sink, error) { 63 return os.OpenFile(u.Path[1:], os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644) 64 }