github.com/demonoid81/containerd@v1.3.4/log/context.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package log 18 19 import ( 20 "context" 21 "sync/atomic" 22 23 "github.com/sirupsen/logrus" 24 ) 25 26 var ( 27 // G is an alias for GetLogger. 28 // 29 // We may want to define this locally to a package to get package tagged log 30 // messages. 31 G = GetLogger 32 33 // L is an alias for the standard logger. 34 L = logrus.NewEntry(logrus.StandardLogger()) 35 ) 36 37 type ( 38 loggerKey struct{} 39 ) 40 41 // TraceLevel is the log level for tracing. Trace level is lower than debug level, 42 // and is usually used to trace detailed behavior of the program. 43 const TraceLevel = logrus.Level(uint32(logrus.DebugLevel + 1)) 44 45 // RFC3339NanoFixed is time.RFC3339Nano with nanoseconds padded using zeros to 46 // ensure the formatted time is always the same number of characters. 47 const RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00" 48 49 // ParseLevel takes a string level and returns the Logrus log level constant. 50 // It supports trace level. 51 func ParseLevel(lvl string) (logrus.Level, error) { 52 if lvl == "trace" { 53 return TraceLevel, nil 54 } 55 return logrus.ParseLevel(lvl) 56 } 57 58 // WithLogger returns a new context with the provided logger. Use in 59 // combination with logger.WithField(s) for great effect. 60 func WithLogger(ctx context.Context, logger *logrus.Entry) context.Context { 61 return context.WithValue(ctx, loggerKey{}, logger) 62 } 63 64 // GetLogger retrieves the current logger from the context. If no logger is 65 // available, the default logger is returned. 66 func GetLogger(ctx context.Context) *logrus.Entry { 67 logger := ctx.Value(loggerKey{}) 68 69 if logger == nil { 70 return L 71 } 72 73 return logger.(*logrus.Entry) 74 } 75 76 // Trace logs a message at level Trace with the log entry passed-in. 77 func Trace(e *logrus.Entry, args ...interface{}) { 78 level := logrus.Level(atomic.LoadUint32((*uint32)(&e.Logger.Level))) 79 if level >= TraceLevel { 80 e.Debug(args...) 81 } 82 } 83 84 // Tracef logs a message at level Trace with the log entry passed-in. 85 func Tracef(e *logrus.Entry, format string, args ...interface{}) { 86 level := logrus.Level(atomic.LoadUint32((*uint32)(&e.Logger.Level))) 87 if level >= TraceLevel { 88 e.Debugf(format, args...) 89 } 90 }