-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathlogger.go
More file actions
109 lines (95 loc) · 2.2 KB
/
logger.go
File metadata and controls
109 lines (95 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package utils
import (
"fmt"
"net/http"
"time"
"github.com/doganarif/govisual/internal/model"
)
const (
green = "\033[32m"
white = "\033[37m"
red = "\033[31m"
blue = "\033[34m"
yellow = "\033[33m"
gray = "\033[90m"
black = "\033[30m"
magenta = "\033[35m"
cyan = "\033[36m"
reset = "\033[0m"
)
func colorizeMethod(method string) string {
if method == "" {
return ""
}
var color string
switch method {
case http.MethodGet:
color = blue
case http.MethodPost:
color = green
case http.MethodPut:
color = yellow
case http.MethodDelete:
color = red
case http.MethodPatch:
color = magenta
case http.MethodHead:
color = gray
case http.MethodOptions:
color = cyan
case http.MethodTrace:
color = white
default:
color = black
}
return fmt.Sprintf("[%s%-7s%s]", color, method, reset)
}
func colorizeStatus(status int) string {
if status < 100 || status > 599 {
return fmt.Sprintf("[%s%3d%s]", red, status, reset)
}
var color string
switch {
case status >= http.StatusContinue && status < http.StatusOK:
color = gray
case status >= http.StatusOK && status < http.StatusMultipleChoices:
color = green
case status >= http.StatusMultipleChoices && status < http.StatusBadRequest:
color = white
case status >= http.StatusBadRequest && status < http.StatusInternalServerError:
color = yellow
default:
color = red
}
return fmt.Sprintf("[%s%3d%s]", color, status, reset)
}
func colorizeDuration(duration time.Duration) string {
if duration < 0 {
return fmt.Sprintf("%s%13v%s", red, duration, reset)
}
var color string
switch {
case duration < 500*time.Millisecond:
color = green
case duration < 1*time.Second:
color = yellow
default:
color = red
}
return fmt.Sprintf("%s%13v%s", color, duration, reset)
}
func LogRequest(reqLog *model.RequestLog) {
// This function logs the request details based on the configuration
if reqLog == nil {
fmt.Println("Warning: Attempted to log nil request log, ignoring")
return
}
fmt.Printf(
"[VIS] %v %s%s %s %#v\n",
reqLog.Timestamp.Format("2006-01-02 15:04:05"),
colorizeMethod(reqLog.Method),
colorizeStatus(reqLog.StatusCode),
colorizeDuration(time.Since(reqLog.Timestamp)),
reqLog.Path,
)
}