1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
13 "github.com/sirupsen/logrus"
14 check "gopkg.in/check.v1"
18 loggerCtxKey = new(int)
19 rootLogger = logrus.New()
22 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
24 // Context returns a new child context such that FromContext(child)
25 // returns the given logger.
26 func Context(ctx context.Context, logger logrus.FieldLogger) context.Context {
27 return context.WithValue(ctx, loggerCtxKey, logger)
30 // FromContext returns the logger suitable for the given context -- the one
31 // attached by contextWithLogger() if applicable, otherwise the
32 // top-level logger with no fields/values.
33 func FromContext(ctx context.Context) logrus.FieldLogger {
35 if logger, ok := ctx.Value(loggerCtxKey).(logrus.FieldLogger); ok {
39 return rootLogger.WithFields(nil)
42 // New returns a new logger with the indicated format and
44 func New(out io.Writer, format, level string) logrus.FieldLogger {
45 logger := logrus.New()
47 setFormat(logger, format)
48 setLevel(logger, level)
52 func TestLogger(c *check.C) logrus.FieldLogger {
53 logger := logrus.New()
54 logger.Out = &logWriter{c.Log}
55 setFormat(logger, "text")
56 if d := os.Getenv("ARVADOS_DEBUG"); d != "0" && d != "" {
57 setLevel(logger, "debug")
59 setLevel(logger, "info")
64 // SetLevel sets the current logging level. See logrus for level
66 func SetLevel(level string) {
67 setLevel(rootLogger, level)
70 func setLevel(logger *logrus.Logger, level string) {
72 } else if lvl, err := logrus.ParseLevel(level); err != nil {
73 logrus.WithField("Level", level).Fatal("unknown log level")
79 // SetFormat sets the current logging format to "json" or "text".
80 func SetFormat(format string) {
81 setFormat(rootLogger, format)
84 func setFormat(logger *logrus.Logger, format string) {
87 logger.Formatter = &logrus.TextFormatter{
89 TimestampFormat: rfc3339NanoFixed,
92 logger.Formatter = &logrus.JSONFormatter{
93 TimestampFormat: rfc3339NanoFixed,
96 logrus.WithField("Format", format).Fatal("unknown log format")
100 // logWriter is an io.Writer that writes by calling a "write log"
101 // function, typically (*check.C)Log().
102 type logWriter struct {
103 logfunc func(...interface{})
106 func (tl *logWriter) Write(buf []byte) (int, error) {
107 tl.logfunc(string(bytes.TrimRight(buf, "\n")))