code.gitea.io/gitea@v1.19.3/modules/log/colors_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][]byte{
    12  	100: ColorBytes(Bold),
    13  	200: ColorBytes(FgGreen),
    14  	300: ColorBytes(FgYellow),
    15  	304: ColorBytes(FgCyan),
    16  	400: ColorBytes(Bold, FgRed),
    17  	401: ColorBytes(Bold, FgMagenta),
    18  	403: ColorBytes(Bold, FgMagenta),
    19  	500: ColorBytes(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 = fgBoldBytes
    30  	}
    31  	if len(s) > 0 {
    32  		return NewColoredValueBytes(s[0], &color)
    33  	}
    34  	return NewColoredValueBytes(status, &color)
    35  }
    36  
    37  var methodToColor = map[string][]byte{
    38  	"GET":    ColorBytes(FgBlue),
    39  	"POST":   ColorBytes(FgGreen),
    40  	"DELETE": ColorBytes(FgRed),
    41  	"PATCH":  ColorBytes(FgCyan),
    42  	"PUT":    ColorBytes(FgYellow, Faint),
    43  	"HEAD":   ColorBytes(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 NewColoredValueBytes(method, &fgBoldBytes)
    51  	}
    52  	return NewColoredValueBytes(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 = [][]byte{
    65  		ColorBytes(FgGreen),
    66  		ColorBytes(Bold),
    67  		ColorBytes(FgYellow),
    68  		ColorBytes(FgRed, Bold),
    69  		ColorBytes(BgRed),
    70  	}
    71  
    72  	wayTooLong = ColorBytes(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 NewColoredValueBytes(str, &durationColors[i])
    84  		}
    85  	}
    86  	return NewColoredValueBytes(str, &wayTooLong)
    87  }