handler.go 10 KB

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