-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging.go
More file actions
90 lines (77 loc) · 2.41 KB
/
Copy pathlogging.go
File metadata and controls
90 lines (77 loc) · 2.41 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
package compass
import (
"fmt"
"net/http"
"time"
)
// Logger defines a minimal logging interface used by the server.
//
// It supports basic log levels (Info, Warn, Error) and a dedicated
// method for logging HTTP requests.
type Logger interface {
Info(message string)
Warn(message string)
Error(message string)
Request(r *http.Request, code int)
}
// SimpleLogger is a basic console logger implementation.
//
// It prints colored log messages to stdout and formats them with
// timestamps and fixed-width prefixes for alignment.
type SimpleLogger struct {
PrefixMaxLength int
}
// log formats and prints a log message with a timestamp and prefix.
//
// The prefix is trimmed or padded to PrefixMaxLength to keep output
// aligned. ANSI color codes are used for styling.
func (s *SimpleLogger) log(color string, prefix string, message string) {
currentTime := time.Now().Format("[2006-01-02 15:04:05]")
if len(prefix) > s.PrefixMaxLength {
prefix = prefix[:s.PrefixMaxLength]
}
prefix = fmt.Sprintf("%-*s", s.PrefixMaxLength, prefix)
fmt.Printf("%s %s%s\033[0m %s\033[0m\n", currentTime, color, prefix, message)
}
// Info logs a message with the "INFO" level.
func (s *SimpleLogger) Info(message string) {
s.log("\x1b[38;2;40;177;249m", "INFO", message)
}
// Warn logs a message with the "WARN" level.
func (s *SimpleLogger) Warn(message string) {
s.log("\033[1;33m", "WARN", message)
}
// Error logs a message with the "ERROR" level.
func (s *SimpleLogger) Error(message string) {
s.log("\033[1;31m", "ERROR", message)
}
// Request logs an HTTP request and its response status code.
//
// The status code is color-coded based on its range:
//
// 2xx = green, 3xx = yellow, 4xx/5xx = red.
//
// It also logs the remote address, method, path, and user agent.
func (s *SimpleLogger) Request(r *http.Request, code int) {
var colorCode string
switch {
case code >= 200 && code < 300:
colorCode = "\033[1;32m"
case code >= 300 && code < 400:
colorCode = "\033[1;33m"
case code >= 400 && code < 600:
colorCode = "\033[1;31m"
default:
colorCode = "\033[1;37m"
}
fmt.Printf(
"\x1b[0;34m%s %s%d\033[0m - \033[0;35m%s %s\033[0m \033[0;37m\"%s\"\033[0m\n",
r.RemoteAddr, colorCode, code, r.Method, r.URL.Path, r.UserAgent(),
)
}
// NewSimpleLogger creates a SimpleLogger with default settings.
//
// The default PrefixMaxLength is set to 5.
func NewSimpleLogger() *SimpleLogger {
return &SimpleLogger{PrefixMaxLength: 5}
}