Files
computer-network/logger/logger.go
T

91 lines
1.6 KiB
Go
Raw Normal View History

2026-03-30 22:05:57 +08:00
package logger
import (
"fmt"
"net"
"sync"
"time"
)
type LogEntry struct {
ClientIP string
Method string
URL string
HTTPVersion string
StatusCode int
Duration time.Duration
Timestamp time.Time
}
type AccessLog struct {
entries []LogEntry
mu sync.Mutex
}
var accessLog = &AccessLog{
entries: make([]LogEntry, 0),
}
func Log(clientIP, method, url, httpVersion string, statusCode int, duration time.Duration) {
entry := LogEntry{
ClientIP: clientIP,
Method: method,
URL: url,
HTTPVersion: httpVersion,
StatusCode: statusCode,
Duration: duration,
Timestamp: time.Now(),
}
accessLog.mu.Lock()
accessLog.entries = append(accessLog.entries, entry)
accessLog.mu.Unlock()
fmt.Printf("[%s] %s %s %s %s %d %v\n",
entry.Timestamp.Format("2006-01-02 15:04:05"),
entry.ClientIP,
entry.Method,
entry.URL,
entry.HTTPVersion,
entry.StatusCode,
entry.Duration.Round(time.Millisecond),
)
}
func GetLogs() []LogEntry {
accessLog.mu.Lock()
defer accessLog.mu.Unlock()
return accessLog.entries
}
func GetRecentLogs(count int) []LogEntry {
accessLog.mu.Lock()
defer accessLog.mu.Unlock()
if count <= 0 || count >= len(accessLog.entries) {
return accessLog.entries
}
start := len(accessLog.entries) - count
return accessLog.entries[start:]
}
func ClearLogs() {
accessLog.mu.Lock()
defer accessLog.mu.Unlock()
accessLog.entries = make([]LogEntry, 0)
fmt.Println("Access logs cleared")
}
func GetClientIP(conn net.Conn) string {
if conn == nil {
return "-"
}
addr := conn.RemoteAddr().String()
host, _, err := net.SplitHostPort(addr)
if err != nil {
return addr
}
return host
}