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