func TestDefaultLevels(t *testing.T) { buf := bytes.Buffer{} logger := levels.New(log.NewLogfmtLogger(&buf)) logger.Debug().Log("msg", "résumé") // of course you'd want to do this if want, have := "level=debug msg=résumé\n", buf.String(); want != have { t.Errorf("want %#v, have %#v", want, have) } buf.Reset() logger.Info().Log("msg", "Åhus") if want, have := "level=info msg=Åhus\n", buf.String(); want != have { t.Errorf("want %#v, have %#v", want, have) } buf.Reset() logger.Error().Log("msg", "© violation") if want, have := "level=error msg=\"© violation\"\n", buf.String(); want != have { t.Errorf("want %#v, have %#v", want, have) } buf.Reset() logger.Crit().Log("msg", " ") if want, have := "level=crit msg=\"\\t\"\n", buf.String(); want != have { t.Errorf("want %#v, have %#v", want, have) } }
func ExampleLevels() { logger := levels.New(log.NewLogfmtLogger(os.Stdout)) logger.Debug("msg", "hello") logger.With("context", "foo").Warn("err", "error") // Output: // level=debug msg=hello // level=warn context=foo err=error }
// StartApplicationSQSConsumer creates a Go-routine that consumes from an SQS queue func StartApplicationSQSConsumer(logger kitlog.Logger, root context.Context, errc chan error, c *config.Configuration) { go func() { ctx, cancel := context.WithCancel(root) defer cancel() l := levlog.New(logger) l.Info().Log("ApplicationSQSConsumer queue", c.QueueName, "transport", "SQS") errc <- consumeMessagesFromQueue(l, ctx, c) }() }
// StartHealthCheckHTTPListener creates a Go-routine that has an HTTP listener for the healthcheck endpoint func StartHealthCheckHTTPListener(logger kitlog.Logger, root context.Context, errc chan error, c *config.Configuration) { go func() { ctx, cancel := context.WithCancel(root) defer cancel() l := levlog.New(logger) l.Info().Log("HealthCheckAddress", c.HealthCheckAddress, "transport", "HTTP/JSON") router := createHealthCheckRouter(logger, ctx, endpoint.NewHealthCheck(c)) errc <- http.ListenAndServe(c.HealthCheckAddress, router) }() }
func TestModifiedLevels(t *testing.T) { buf := bytes.Buffer{} logger := levels.New( log.NewJSONLogger(&buf), levels.Key("l"), levels.DebugValue("dbg"), ) logger.With("easter_island", "176°").Debug("msg", "moai") if want, have := `{"easter_island":"176°","l":"dbg","msg":"moai"}`+"\n", buf.String(); want != have { t.Errorf("want %#v, have %#v", want, have) } }
// StartApplicationHTTPListener creates a Go-routine that has an HTTP listener sensor readings func StartApplicationHTTPListener(logger kitlog.Logger, root context.Context, errc chan error, c *config.Configuration) { go func() { ctx, cancel := context.WithCancel(root) defer cancel() l := levlog.New(logger) l.Info().Log("ApplicationAddress", c.ApplicationAddress, "transport", "HTTP/JSON") router := createApplicationRouter(logger, ctx, c, endpoint.NewSensorReadingServicer(c)) errc <- http.ListenAndServe(c.ApplicationAddress, router) }() }
func init() { termLog = log.NewLogfmtLogger(os.Stderr) if term.IsTerminal(os.Stderr) { termLog = term.NewLogger( os.Stderr, log.NewLogfmtLogger, kithlp.NewLevelColorer("level", nil), ) } logBase.Swap(termLog) lg := kithlp.StringifyLogger{logBase} Logger = log.NewContext(lg).With("ts", log.DefaultTimestampUTC, "caller", log.Caller(4)) logger = levels.New(Logger) stdlog.SetOutput(log.NewStdlibAdapter(logBase)) converter.Logger.Swap(Logger) }
func main() { var ( listen = flag.String("listen", ":8080", "HTTP listen address") // proxy = flag.String("proxy", "", "Optional comma-separated list of URLs to proxy uppercase requests") ) flag.Parse() var logger log.Logger logger = log.NewLogfmtLogger(os.Stderr) logger = log.NewContext(logger).With("listen", *listen).With("caller", log.DefaultCaller) loglevel := levels.New(logger) ctx := context.Background() redisURL := os.Getenv("REDIS_URL") redisPassword := os.Getenv("REDIS_PASSWORD") if redisURL == "" || redisPassword == "" { _ = loglevel.Crit("err", "missing REDIS connection information") return } infra, err := BuildInfrastructure(InfrastructureOptions{ DialURL: os.Getenv("REDIS_URL"), DialOption: []redis.DialOption{redis.DialPassword(redisPassword)}, }) if err != nil { _ = loglevel.Crit("err", fmt.Sprintf("Infrastructure error: %v", err)) return } defer infra.conn.Close() var svc CacheService svc = cacheService{} svc = loggingMiddleware(logger)(svc) cacheHandler := httptransport.NewServer( ctx, makeCacheEndpoint(svc), decodeCacheRequest, encodeResponse, ) http.Handle("/cache", cacheHandler) _ = logger.Log("msg", "HTTP", "addr", *listen) _ = logger.Log("err", http.ListenAndServe(*listen, nil)) }
package converter import ( "os" "os/exec" "path/filepath" "time" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/levels" "github.com/stvp/go-toml-config" ) // Swappable logger, var Logger = new(log.SwapLogger) var logger = levels.New(log.NewContext(Logger).With("lib", "converter")) func init() { Logger.Swap(log.NewNopLogger()) } var ( // ConfPdftk is the path for PdfTk ConfPdftk = config.String("pdftk", "pdftk") // ConfPdfseparate is the path for pdfseparate (member of poppler-utils ConfPdfseparate = config.String("pdfseparate", "pdfseparate") // ConfLoffice is the path for LibreOffice ConfLoffice = config.String("loffice", "loffice")
package leveledLogger import ( "bytes" "testing" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/levels" ) var ( adapter = log.NewStdlibAdapter(log.NewNopLogger(), log.TimestampKey(""), log.FileKey(""), log.MessageKey(""), ) baseLogger = log.NewLogfmtLogger(adapter) kitleveler = levels.New(baseLogger) ) func BenchmarkInfo_KitLevels(b *testing.B) { for i := 0; i < b.N; i++ { kitleveler.Info().Log( "key1", "first value is main message string", "key2", "file:line", "key3", "timestamp", "key4", "fake error string in case an error occurred", ) } } var ( buffer = new(bytes.Buffer)
"fmt" stdlog "log" "net/http" "os" "strings" "sync" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/levels" "github.com/juju/persistent-cookiejar" "github.com/spf13/cobra" ) var ( logger = log.NewLogfmtLogger(os.Stderr) Log = levels.New(logger) ) type config struct { SystemID string BaseURL, DataURL, LogonURL string CookieJarPath string dateFormat string initURLs sync.Once jar *cookiejar.Jar jarMu sync.Mutex *http.Client initClient sync.Once }
"github.com/tgulacsi/go/temp" "gopkg.in/errgo.v1" ) var ( // Logger is the base logger, can be swapped - defaults to NopLogger. Logger = new(log.SwapLogger) // CheckEncoding is true if we should check Base64 encodings CheckEncoding = true // SaveBadInput is true if we should save bad input SaveBadInput = false // logger is the package-level logger. logger = levels.New(log.NewContext(Logger).With("lib", "i18nmail")) ) func init() { Logger.Swap(log.NewNopLogger()) } // TodoFunc is the type of the function called by Walk and WalkMultipart. type TodoFunc func(mp MailPart) error // sequence is a global sequence for numbering mail parts. var sequence uint64 func nextSeq() uint64 { return atomic.AddUint64(&sequence, 1) }
// application. InfoLevel // DebugLevel level. Usually only enabled when debugging. Very verbose // logging. DebugLevel ) // currentLevel has a default and it's updated later by levelFlag var currentLevel = InfoLevel var ( logger = log.NewLogfmtLogger(os.Stderr) ctx = log.NewContext(logger).With("ts", log.DefaultTimestampUTC) // Logger is the global application logger Logger = levels.New(ctx).With("caller", log.Caller(5)) ) type levelFlag struct{} // String implements flag.Value. func (f levelFlag) String() string { return fmt.Sprint(currentLevel) } // Set implements flag.Value. func (f levelFlag) Set(level string) (err error) { currentLevel, err = ParseLevel(level) return err }
func NoopLogger() *CoreLogger { return NewCoreLogger(levels.New(kitlog.NewNopLogger())) }
func LogfmtLoggerTo(writer io.Writer) *CoreLogger { return NewCoreLogger(levels.New(kitlog.NewLogfmtLogger(writer))) }
func JSONLoggerTo(writer io.Writer) *CoreLogger { return NewCoreLogger(levels.New(kitlog.NewJSONLogger(writer))) }