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