update-api/log/logger.go

88 lines
1.5 KiB
Go

package log
import (
"encoding/json"
"fmt"
"time"
"github.com/gin-gonic/gin"
)
var LogSeverity = INFO
func GinJsonLogger() gin.HandlerFunc {
Debug("creating logger for gin")
return func(c *gin.Context) {
start := time.Now()
c.Next()
duration := time.Since(start)
status := c.Writer.Status()
path := c.Request.URL.Path
ginEntry := ginJsonLogEntry{
Status: status,
Duration: duration.String(),
ClientIP: c.ClientIP(),
Method: c.Request.Method,
Path: path,
}
LogWithSource(INFO, "gin", ginEntry)
}
}
func LogWithSource(level Severity, source string, message interface{}, a ...any) {
if LogSeverity.weight > level.weight {
return
}
var parsed interface{}
switch t := message.(type) {
case string:
parsed = fmt.Sprintf(t, a...)
default:
parsed = t
}
entry := logEntry{
Time: time.Now().Format(time.RFC3339),
Severity: level.name,
Message: parsed,
Source: source,
}
jsonEntry, err := json.Marshal(entry)
if err != nil {
panic(fmt.Sprintf("bruh moment: %s", err.Error()))
}
fmt.Println(string(jsonEntry))
}
func Log(level Severity, message interface{}, a ...any) {
LogWithSource(level, "application", message, a...)
}
func Debug(message interface{}, a ...any) {
Log(DEBUG, message, a...)
}
func Info(message interface{}, a ...any) {
Log(INFO, message, a...)
}
func Warning(message interface{}, a ...any) {
Log(WARNING, message, a...)
}
func Error(message interface{}, a ...any) {
Log(ERROR, message, a...)
}
func Fatal(message interface{}, a ...any) {
Log(FATAL, message, a...)
}