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