logger.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package tango
  2. import (
  3. "io"
  4. "time"
  5. "github.com/lunny/log"
  6. )
  7. type Logger interface {
  8. Debugf(format string, v ...interface{})
  9. Debug(v ...interface{})
  10. Infof(format string, v ...interface{})
  11. Info(v ...interface{})
  12. Warnf(format string, v ...interface{})
  13. Warn(v ...interface{})
  14. Errorf(format string, v ...interface{})
  15. Error(v ...interface{})
  16. }
  17. func NewLogger(out io.Writer) Logger {
  18. l := log.New(out, "[tango] ", log.Ldefault())
  19. if Env == Dev {
  20. l.SetOutputLevel(log.Ldebug)
  21. } else {
  22. l.SetOutputLevel(log.Linfo)
  23. }
  24. return l
  25. }
  26. type LogInterface interface {
  27. SetLogger(Logger)
  28. }
  29. type Log struct {
  30. Logger
  31. }
  32. func (l *Log) SetLogger(log Logger) {
  33. l.Logger = log
  34. }
  35. func Logging() HandlerFunc {
  36. return func(ctx *Context) {
  37. start := time.Now()
  38. p := ctx.Req().URL.Path
  39. if len(ctx.Req().URL.RawQuery) > 0 {
  40. p = p + "?" + ctx.Req().URL.RawQuery
  41. }
  42. ctx.Debug("Started", ctx.Req().Method, p, "for", ctx.Req().RemoteAddr)
  43. if action := ctx.Action(); action != nil {
  44. if l, ok := action.(LogInterface); ok {
  45. l.SetLogger(ctx.Logger)
  46. }
  47. }
  48. ctx.Next()
  49. if !ctx.Written() {
  50. if ctx.Result == nil {
  51. ctx.Result = NotFound()
  52. }
  53. ctx.HandleError()
  54. }
  55. statusCode := ctx.Status()
  56. escape := time.Now().Sub(start)
  57. if statusCode >= 200 && statusCode < 400 {
  58. ctx.Info(ctx.Req().Method, statusCode, escape, p)
  59. } else {
  60. ctx.Error(ctx.Req().Method, statusCode, escape, p, ctx.Result)
  61. }
  62. }
  63. }