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.

colors_router.go 2.2KB

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