github.com/thanos-io/thanos@v0.32.5/pkg/logging/logger.go (about) 1 // Copyright (c) The Thanos Authors. 2 // Licensed under the Apache License 2.0. 3 4 package logging 5 6 import ( 7 "os" 8 9 "github.com/go-kit/log" 10 "github.com/go-kit/log/level" 11 ) 12 13 const ( 14 LogFormatLogfmt = "logfmt" 15 LogFormatJSON = "json" 16 ) 17 18 // NewLogger returns a log.Logger that prints in the provided format at the 19 // provided level with a UTC timestamp and the caller of the log entry. If non 20 // empty, the debug name is also appended as a field to all log lines. Panics 21 // if the log level is not error, warn, info or debug. Log level is expected to 22 // be validated before passed to this function. 23 func NewLogger(logLevel, logFormat, debugName string) log.Logger { 24 var ( 25 logger log.Logger 26 lvl level.Option 27 ) 28 29 switch logLevel { 30 case "error": 31 lvl = level.AllowError() 32 case "warn": 33 lvl = level.AllowWarn() 34 case "info": 35 lvl = level.AllowInfo() 36 case "debug": 37 lvl = level.AllowDebug() 38 default: 39 // This enum is already checked and enforced by flag validations, so 40 // this should never happen. 41 panic("unexpected log level") 42 } 43 44 logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) 45 if logFormat == LogFormatJSON { 46 logger = log.NewJSONLogger(log.NewSyncWriter(os.Stderr)) 47 } 48 49 // Sort the logger chain to avoid expensive log.Valuer evaluation for disallowed level. 50 // Ref: https://github.com/go-kit/log/issues/14#issuecomment-945038252 51 logger = log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.Caller(5)) 52 logger = level.NewFilter(logger, lvl) 53 54 if debugName != "" { 55 logger = log.With(logger, "name", debugName) 56 } 57 58 return logger 59 }