logger.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. l.SetOutputLevel(log.Ldebug)
  20. return l
  21. }
  22. type LogInterface interface {
  23. SetLogger(Logger)
  24. }
  25. type Log struct {
  26. Logger
  27. }
  28. func (l *Log) SetLogger(log Logger) {
  29. l.Logger = log
  30. }
  31. type Logging struct {
  32. logger Logger
  33. }
  34. func NewLogging(logger Logger) *Logging {
  35. return &Logging{
  36. logger: logger,
  37. }
  38. }
  39. func (l *Logging) Inject(o interface{}) {
  40. if g, ok := o.(LogInterface); ok {
  41. g.SetLogger(l.logger)
  42. }
  43. }
  44. func (itor *Logging) Handle(ctx *Context) {
  45. start := time.Now()
  46. itor.logger.Debug("Started", ctx.Req().Method,
  47. ctx.Req().URL.Path, "for", ctx.Req().RemoteAddr)
  48. if action := ctx.Action(); action != nil {
  49. if l, ok := action.(LogInterface); ok {
  50. l.SetLogger(itor.logger)
  51. }
  52. }
  53. ctx.Next()
  54. if ctx.Written() {
  55. statusCode := ctx.Status()
  56. requestPath := ctx.Req().URL.Path
  57. escape := time.Now().Sub(start)
  58. if statusCode >= 200 && statusCode < 400 {
  59. itor.logger.Info(ctx.Req().Method, statusCode, escape, requestPath)
  60. } else {
  61. itor.logger.Error(ctx.Req().Method, statusCode, escape, requestPath)
  62. }
  63. }
  64. }