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