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