log.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. logrus "github.com/sirupsen/logrus"
  6. )
  7. func initLog() error {
  8. logFormat := "pretty"
  9. strEnvConfig(&logFormat, "IMGPROXY_LOG_FORMAT")
  10. switch logFormat {
  11. case "structured":
  12. logrus.SetFormatter(&logStructuredFormatter{})
  13. case "json":
  14. logrus.SetFormatter(&logrus.JSONFormatter{})
  15. default:
  16. logrus.SetFormatter(newLogPrettyFormatter())
  17. }
  18. logLevel := "info"
  19. strEnvConfig(&logLevel, "IMGPROXY_LOG_LEVEL")
  20. levelLogLevel, err := logrus.ParseLevel(logLevel)
  21. if err != nil {
  22. levelLogLevel = logrus.InfoLevel
  23. }
  24. logrus.SetLevel(levelLogLevel)
  25. if isSyslogEnabled() {
  26. slHook, err := newSyslogHook()
  27. if err != nil {
  28. return fmt.Errorf("Unable to connect to syslog daemon: %s", err)
  29. }
  30. logrus.AddHook(slHook)
  31. }
  32. return nil
  33. }
  34. func logRequest(reqID string, r *http.Request) {
  35. path := r.RequestURI
  36. logrus.WithFields(logrus.Fields{
  37. "request_id": reqID,
  38. "method": r.Method,
  39. }).Infof("Started %s", path)
  40. }
  41. func logResponse(reqID string, r *http.Request, status int, err *imgproxyError, imageURL *string, po *processingOptions) {
  42. var level logrus.Level
  43. switch {
  44. case status >= 500:
  45. level = logrus.ErrorLevel
  46. case status >= 400:
  47. level = logrus.WarnLevel
  48. default:
  49. level = logrus.InfoLevel
  50. }
  51. fields := logrus.Fields{
  52. "request_id": reqID,
  53. "method": r.Method,
  54. "status": status,
  55. }
  56. if err != nil {
  57. fields["error"] = err
  58. if stack := err.FormatStack(); len(stack) > 0 {
  59. fields["stack"] = stack
  60. }
  61. }
  62. if imageURL != nil {
  63. fields["image_url"] = *imageURL
  64. }
  65. if po != nil {
  66. fields["processing_options"] = po
  67. }
  68. logrus.WithFields(fields).Logf(
  69. level,
  70. "Completed in %s %s", getTimerSince(r.Context()), r.RequestURI,
  71. )
  72. }
  73. func logNotice(f string, args ...interface{}) {
  74. logrus.Infof(f, args...)
  75. }
  76. func logWarning(f string, args ...interface{}) {
  77. logrus.Warnf(f, args...)
  78. }
  79. func logError(f string, args ...interface{}) {
  80. logrus.Errorf(f, args...)
  81. }
  82. func logFatal(f string, args ...interface{}) {
  83. logrus.Fatalf(f, args...)
  84. }
  85. func logDebug(f string, args ...interface{}) {
  86. logrus.Debugf(f, args...)
  87. }