github.com/nya3jp/tast@v0.0.0-20230601000426-85c8e4d83a9b/src/go.chromium.org/tast/core/internal/logging/logger.go (about) 1 // Copyright 2021 The ChromiumOS Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package logging 6 7 import ( 8 "sync" 9 "time" 10 ) 11 12 // Level indicates a logging level. A larger level value means a log is more 13 // important. 14 type Level int 15 16 const ( 17 // LevelDebug represents the DEBUG level. 18 LevelDebug Level = iota 19 // LevelInfo represents the INFO level. 20 LevelInfo 21 ) 22 23 // Logger defines the interface for loggers that consume logs sent via 24 // context.Context. 25 // 26 // You can create a new context with a Logger attached by AttachLogger. The 27 // attached logger will consume all logs sent to the context, as well as those 28 // logs sent to its descendant contexts as long as you don't attach another 29 // logger to a descendant context with no propagation. See AttachLogger for more 30 // details. 31 type Logger interface { 32 // Log gets called for a log entry. 33 Log(level Level, ts time.Time, msg string) 34 } 35 36 // MultiLogger is a Logger that copies logs to multiple underlying loggers. 37 // A logger can be added and removed from MultiLogger at any time. 38 type MultiLogger struct { 39 mu sync.Mutex 40 loggers []Logger 41 } 42 43 // NewMultiLogger creates a new MultiLogger with a specified initial set of 44 // underlying loggers. 45 func NewMultiLogger(loggers ...Logger) *MultiLogger { 46 return &MultiLogger{loggers: loggers} 47 } 48 49 // Log copies a log to the current underlying loggers. 50 func (ml *MultiLogger) Log(level Level, ts time.Time, msg string) { 51 ml.mu.Lock() 52 defer ml.mu.Unlock() 53 for _, logger := range ml.loggers { 54 logger.Log(level, ts, msg) 55 } 56 } 57 58 // AddLogger adds a logger to the set of underlying loggers. 59 func (ml *MultiLogger) AddLogger(logger Logger) { 60 ml.mu.Lock() 61 defer ml.mu.Unlock() 62 ml.loggers = append(ml.loggers, logger) 63 } 64 65 // RemoveLogger removes a logger from the set of underlying loggers. 66 func (ml *MultiLogger) RemoveLogger(logger Logger) { 67 ml.mu.Lock() 68 defer ml.mu.Unlock() 69 j := 0 70 for i, l := range ml.loggers { 71 if l == logger { 72 continue 73 } 74 ml.loggers[j] = ml.loggers[i] 75 j++ 76 } 77 ml.loggers = ml.loggers[:j] 78 }