github.com/carter-ya/go-ethereum@v0.0.0-20230628080049-d2309be3983b/log/handler.go (about) 1 package log 2 3 import ( 4 "fmt" 5 "io" 6 "net" 7 "os" 8 "reflect" 9 "sync" 10 11 "github.com/go-stack/stack" 12 ) 13 14 // Handler defines where and how log records are written. 15 // A Logger prints its log records by writing to a Handler. 16 // Handlers are composable, providing you great flexibility in combining 17 // them to achieve the logging structure that suits your applications. 18 type Handler interface { 19 Log(r *Record) error 20 } 21 22 // FuncHandler returns a Handler that logs records with the given 23 // function. 24 func FuncHandler(fn func(r *Record) error) Handler { 25 return funcHandler(fn) 26 } 27 28 type funcHandler func(r *Record) error 29 30 func (h funcHandler) Log(r *Record) error { 31 return h(r) 32 } 33 34 // StreamHandler writes log records to an io.Writer 35 // with the given format. StreamHandler can be used 36 // to easily begin writing log records to other 37 // outputs. 38 // 39 // StreamHandler wraps itself with LazyHandler and SyncHandler 40 // to evaluate Lazy objects and perform safe concurrent writes. 41 func StreamHandler(wr io.Writer, fmtr Format) Handler { 42 h := FuncHandler(func(r *Record) error { 43 _, err := wr.Write(fmtr.Format(r)) 44 return err 45 }) 46 return LazyHandler(SyncHandler(h)) 47 } 48 49 // SyncHandler can be wrapped around a handler to guarantee that 50 // only a single Log operation can proceed at a time. It's necessary 51 // for thread-safe concurrent writes. 52 func SyncHandler(h Handler) Handler { 53 var mu sync.Mutex 54 return FuncHandler(func(r *Record) error { 55 mu.Lock() 56 defer mu.Unlock() 57 58 return h.Log(r) 59 }) 60 } 61 62 // FileHandler returns a handler which writes log records to the give file 63 // using the given format. If the path 64 // already exists, FileHandler will append to the given file. If it does not, 65 // FileHandler will create the file with mode 0644. 66 func FileHandler(path string, fmtr Format) (Handler, error) { 67 f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) 68 if err != nil { 69 return nil, err 70 } 71 return closingHandler{f, StreamHandler(f, fmtr)}, nil 72 } 73 74 // NetHandler opens a socket to the given address and writes records 75 // over the connection. 76 func NetHandler(network, addr string, fmtr Format) (Handler, error) { 77 conn, err := net.Dial(network, addr) 78 if err != nil { 79 return nil, err 80 } 81 82 return closingHandler{conn, StreamHandler(conn, fmtr)}, nil 83 } 84 85 // XXX: closingHandler is essentially unused at the moment 86 // it's meant for a future time when the Handler interface supports 87 // a possible Close() operation 88 type closingHandler struct { 89 io.WriteCloser 90 Handler 91 } 92 93 func (h *closingHandler) Close() error { 94 return h.WriteCloser.Close() 95 } 96 97 // CallerFileHandler returns a Handler that adds the line number and file of 98 // the calling function to the context with key "caller". 99 func CallerFileHandler(h Handler) Handler { 100 return FuncHandler(func(r *Record) error { 101 r.Ctx = append(r.Ctx, "caller", fmt.Sprint(r.Call)) 102 return h.Log(r) 103 }) 104 } 105 106 // CallerFuncHandler returns a Handler that adds the calling function name to 107 // the context with key "fn". 108 func CallerFuncHandler(h Handler) Handler { 109 return FuncHandler(func(r *Record) error { 110 r.Ctx = append(r.Ctx, "fn", formatCall("%+n", r.Call)) 111 return h.Log(r) 112 }) 113 } 114 115 // This function is here to please go vet on Go < 1.8. 116 func formatCall(format string, c stack.Call) string { 117 return fmt.Sprintf(format, c) 118 } 119 120 // CallerStackHandler returns a Handler that adds a stack trace to the context 121 // with key "stack". The stack trace is formatted as a space separated list of 122 // call sites inside matching []'s. The most recent call site is listed first. 123 // Each call site is formatted according to format. See the documentation of 124 // package github.com/go-stack/stack for the list of supported formats. 125 func CallerStackHandler(format string, h Handler) Handler { 126 return FuncHandler(func(r *Record) error { 127 s := stack.Trace().TrimBelow(r.Call).TrimRuntime() 128 if len(s) > 0 { 129 r.Ctx = append(r.Ctx, "stack", fmt.Sprintf(format, s)) 130 } 131 return h.Log(r) 132 }) 133 } 134 135 // FilterHandler returns a Handler that only writes records to the 136 // wrapped Handler if the given function evaluates true. For example, 137 // to only log records where the 'err' key is not nil: 138 // 139 // logger.SetHandler(FilterHandler(func(r *Record) bool { 140 // for i := 0; i < len(r.Ctx); i += 2 { 141 // if r.Ctx[i] == "err" { 142 // return r.Ctx[i+1] != nil 143 // } 144 // } 145 // return false 146 // }, h)) 147 func FilterHandler(fn func(r *Record) bool, h Handler) Handler { 148 return FuncHandler(func(r *Record) error { 149 if fn(r) { 150 return h.Log(r) 151 } 152 return nil 153 }) 154 } 155 156 // MatchFilterHandler returns a Handler that only writes records 157 // to the wrapped Handler if the given key in the logged 158 // context matches the value. For example, to only log records 159 // from your ui package: 160 // 161 // log.MatchFilterHandler("pkg", "app/ui", log.StdoutHandler) 162 func MatchFilterHandler(key string, value interface{}, h Handler) Handler { 163 return FilterHandler(func(r *Record) (pass bool) { 164 switch key { 165 case r.KeyNames.Lvl: 166 return r.Lvl == value 167 case r.KeyNames.Time: 168 return r.Time == value 169 case r.KeyNames.Msg: 170 return r.Msg == value 171 } 172 173 for i := 0; i < len(r.Ctx); i += 2 { 174 if r.Ctx[i] == key { 175 return r.Ctx[i+1] == value 176 } 177 } 178 return false 179 }, h) 180 } 181 182 // LvlFilterHandler returns a Handler that only writes 183 // records which are less than the given verbosity 184 // level to the wrapped Handler. For example, to only 185 // log Error/Crit records: 186 // 187 // log.LvlFilterHandler(log.LvlError, log.StdoutHandler) 188 func LvlFilterHandler(maxLvl Lvl, h Handler) Handler { 189 return FilterHandler(func(r *Record) (pass bool) { 190 return r.Lvl <= maxLvl 191 }, h) 192 } 193 194 // MultiHandler dispatches any write to each of its handlers. 195 // This is useful for writing different types of log information 196 // to different locations. For example, to log to a file and 197 // standard error: 198 // 199 // log.MultiHandler( 200 // log.Must.FileHandler("/var/log/app.log", log.LogfmtFormat()), 201 // log.StderrHandler) 202 func MultiHandler(hs ...Handler) Handler { 203 return FuncHandler(func(r *Record) error { 204 for _, h := range hs { 205 // what to do about failures? 206 h.Log(r) 207 } 208 return nil 209 }) 210 } 211 212 // FailoverHandler writes all log records to the first handler 213 // specified, but will failover and write to the second handler if 214 // the first handler has failed, and so on for all handlers specified. 215 // For example you might want to log to a network socket, but failover 216 // to writing to a file if the network fails, and then to 217 // standard out if the file write fails: 218 // 219 // log.FailoverHandler( 220 // log.Must.NetHandler("tcp", ":9090", log.JSONFormat()), 221 // log.Must.FileHandler("/var/log/app.log", log.LogfmtFormat()), 222 // log.StdoutHandler) 223 // 224 // All writes that do not go to the first handler will add context with keys of 225 // the form "failover_err_{idx}" which explain the error encountered while 226 // trying to write to the handlers before them in the list. 227 func FailoverHandler(hs ...Handler) Handler { 228 return FuncHandler(func(r *Record) error { 229 var err error 230 for i, h := range hs { 231 err = h.Log(r) 232 if err == nil { 233 return nil 234 } 235 r.Ctx = append(r.Ctx, fmt.Sprintf("failover_err_%d", i), err) 236 } 237 238 return err 239 }) 240 } 241 242 // ChannelHandler writes all records to the given channel. 243 // It blocks if the channel is full. Useful for async processing 244 // of log messages, it's used by BufferedHandler. 245 func ChannelHandler(recs chan<- *Record) Handler { 246 return FuncHandler(func(r *Record) error { 247 recs <- r 248 return nil 249 }) 250 } 251 252 // BufferedHandler writes all records to a buffered 253 // channel of the given size which flushes into the wrapped 254 // handler whenever it is available for writing. Since these 255 // writes happen asynchronously, all writes to a BufferedHandler 256 // never return an error and any errors from the wrapped handler are ignored. 257 func BufferedHandler(bufSize int, h Handler) Handler { 258 recs := make(chan *Record, bufSize) 259 go func() { 260 for m := range recs { 261 _ = h.Log(m) 262 } 263 }() 264 return ChannelHandler(recs) 265 } 266 267 // LazyHandler writes all values to the wrapped handler after evaluating 268 // any lazy functions in the record's context. It is already wrapped 269 // around StreamHandler and SyslogHandler in this library, you'll only need 270 // it if you write your own Handler. 271 func LazyHandler(h Handler) Handler { 272 return FuncHandler(func(r *Record) error { 273 // go through the values (odd indices) and reassign 274 // the values of any lazy fn to the result of its execution 275 hadErr := false 276 for i := 1; i < len(r.Ctx); i += 2 { 277 lz, ok := r.Ctx[i].(Lazy) 278 if ok { 279 v, err := evaluateLazy(lz) 280 if err != nil { 281 hadErr = true 282 r.Ctx[i] = err 283 } else { 284 if cs, ok := v.(stack.CallStack); ok { 285 v = cs.TrimBelow(r.Call).TrimRuntime() 286 } 287 r.Ctx[i] = v 288 } 289 } 290 } 291 292 if hadErr { 293 r.Ctx = append(r.Ctx, errorKey, "bad lazy") 294 } 295 296 return h.Log(r) 297 }) 298 } 299 300 func evaluateLazy(lz Lazy) (interface{}, error) { 301 t := reflect.TypeOf(lz.Fn) 302 303 if t.Kind() != reflect.Func { 304 return nil, fmt.Errorf("INVALID_LAZY, not func: %+v", lz.Fn) 305 } 306 307 if t.NumIn() > 0 { 308 return nil, fmt.Errorf("INVALID_LAZY, func takes args: %+v", lz.Fn) 309 } 310 311 if t.NumOut() == 0 { 312 return nil, fmt.Errorf("INVALID_LAZY, no func return val: %+v", lz.Fn) 313 } 314 315 value := reflect.ValueOf(lz.Fn) 316 results := value.Call([]reflect.Value{}) 317 if len(results) == 1 { 318 return results[0].Interface(), nil 319 } 320 values := make([]interface{}, len(results)) 321 for i, v := range results { 322 values[i] = v.Interface() 323 } 324 return values, nil 325 } 326 327 // DiscardHandler reports success for all writes but does nothing. 328 // It is useful for dynamically disabling logging at runtime via 329 // a Logger's SetHandler method. 330 func DiscardHandler() Handler { 331 return FuncHandler(func(r *Record) error { 332 return nil 333 }) 334 } 335 336 // Must provides the following Handler creation functions 337 // which instead of returning an error parameter only return a Handler 338 // and panic on failure: FileHandler, NetHandler, SyslogHandler, SyslogNetHandler 339 var Must muster 340 341 func must(h Handler, err error) Handler { 342 if err != nil { 343 panic(err) 344 } 345 return h 346 } 347 348 type muster struct{} 349 350 func (m muster) FileHandler(path string, fmtr Format) Handler { 351 return must(FileHandler(path, fmtr)) 352 } 353 354 func (m muster) NetHandler(network, addr string, fmtr Format) Handler { 355 return must(NetHandler(network, addr, fmtr)) 356 }