8784: Fix test for latest firefox.
[arvados.git] / sdk / go / ctxlog / log.go
1 package ctxlog
2
3 import (
4         "context"
5
6         "github.com/Sirupsen/logrus"
7 )
8
9 var (
10         loggerCtxKey = new(int)
11         rootLogger   = logrus.New()
12 )
13
14 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
15
16 // Context returns a new child context such that FromContext(child)
17 // returns the given logger.
18 func Context(ctx context.Context, logger *logrus.Entry) context.Context {
19         return context.WithValue(ctx, loggerCtxKey, logger)
20 }
21
22 // FromContext returns the logger suitable for the given context -- the one
23 // attached by contextWithLogger() if applicable, otherwise the
24 // top-level logger with no fields/values.
25 func FromContext(ctx context.Context) *logrus.Entry {
26         if ctx != nil {
27                 if logger, ok := ctx.Value(loggerCtxKey).(*logrus.Entry); ok {
28                         return logger
29                 }
30         }
31         return rootLogger.WithFields(nil)
32 }
33
34 // SetLevel sets the current logging level. See logrus for level
35 // names.
36 func SetLevel(level string) {
37         lvl, err := logrus.ParseLevel(level)
38         if err != nil {
39                 logrus.Fatal(err)
40         }
41         rootLogger.Level = lvl
42 }
43
44 // SetFormat sets the current logging format to "json" or "text".
45 func SetFormat(format string) {
46         switch format {
47         case "text":
48                 rootLogger.Formatter = &logrus.TextFormatter{
49                         FullTimestamp:   true,
50                         TimestampFormat: rfc3339NanoFixed,
51                 }
52         case "json":
53                 rootLogger.Formatter = &logrus.JSONFormatter{
54                         TimestampFormat: rfc3339NanoFixed,
55                 }
56         default:
57                 logrus.WithField("LogFormat", format).Fatal("unknown log format")
58         }
59 }