You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

color_router.go 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package log
  4. import (
  5. "fmt"
  6. "time"
  7. )
  8. var statusToColor = map[int][]ColorAttribute{
  9. 100: {Bold},
  10. 200: {FgGreen},
  11. 300: {FgYellow},
  12. 304: {FgCyan},
  13. 400: {Bold, FgRed},
  14. 401: {Bold, FgMagenta},
  15. 403: {Bold, FgMagenta},
  16. 500: {Bold, BgRed},
  17. }
  18. // ColoredStatus adds colors for HTTP status
  19. func ColoredStatus(status int, s ...string) *ColoredValue {
  20. color, ok := statusToColor[status]
  21. if !ok {
  22. color, ok = statusToColor[(status/100)*100]
  23. }
  24. if !ok {
  25. color = []ColorAttribute{Bold}
  26. }
  27. if len(s) > 0 {
  28. return NewColoredValue(s[0], color...)
  29. }
  30. return NewColoredValue(status, color...)
  31. }
  32. var methodToColor = map[string][]ColorAttribute{
  33. "GET": {FgBlue},
  34. "POST": {FgGreen},
  35. "DELETE": {FgRed},
  36. "PATCH": {FgCyan},
  37. "PUT": {FgYellow, Faint},
  38. "HEAD": {FgBlue, Faint},
  39. }
  40. // ColoredMethod adds colors for HTTP methods on log
  41. func ColoredMethod(method string) *ColoredValue {
  42. color, ok := methodToColor[method]
  43. if !ok {
  44. return NewColoredValue(method, Bold)
  45. }
  46. return NewColoredValue(method, color...)
  47. }
  48. var (
  49. durations = []time.Duration{
  50. 10 * time.Millisecond,
  51. 100 * time.Millisecond,
  52. 1 * time.Second,
  53. 5 * time.Second,
  54. 10 * time.Second,
  55. }
  56. durationColors = [][]ColorAttribute{
  57. {FgGreen},
  58. {Bold},
  59. {FgYellow},
  60. {FgRed, Bold},
  61. {BgRed},
  62. }
  63. wayTooLong = BgMagenta
  64. )
  65. // ColoredTime converts the provided time to a ColoredValue for logging. The duration is always formatted in milliseconds.
  66. func ColoredTime(duration time.Duration) *ColoredValue {
  67. // the output of duration in Millisecond is more readable:
  68. // * before: "100.1ms" "100.1μs" "100.1s"
  69. // * better: "100.1ms" "0.1ms" "100100.0ms", readers can compare the values at first glance.
  70. str := fmt.Sprintf("%.1fms", float64(duration.Microseconds())/1000)
  71. for i, k := range durations {
  72. if duration < k {
  73. return NewColoredValue(str, durationColors[i]...)
  74. }
  75. }
  76. return NewColoredValue(str, wayTooLong)
  77. }