mirror of https://github.com/synctv-org/synctv
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
1.7 KiB
Go
82 lines
1.7 KiB
Go
package middlewares
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
func NewLog(l *logrus.Logger) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
c.Set("log", &logrus.Entry{
|
|
Logger: l,
|
|
})
|
|
|
|
start := time.Now()
|
|
path := c.Request.URL.Path
|
|
raw := c.Request.URL.RawQuery
|
|
|
|
c.Next()
|
|
|
|
param := gin.LogFormatterParams{
|
|
Request: c.Request,
|
|
Keys: c.Keys,
|
|
}
|
|
|
|
// Stop timer
|
|
param.TimeStamp = time.Now()
|
|
param.Latency = param.TimeStamp.Sub(start)
|
|
|
|
param.ClientIP = c.ClientIP()
|
|
param.Method = c.Request.Method
|
|
param.StatusCode = c.Writer.Status()
|
|
param.ErrorMessage = c.Errors.ByType(gin.ErrorTypePrivate).String()
|
|
|
|
param.BodySize = c.Writer.Size()
|
|
|
|
if raw != "" {
|
|
path = path + "?" + raw
|
|
}
|
|
|
|
param.Path = path
|
|
|
|
logColor(c.MustGet("log").(*logrus.Entry), param)
|
|
}
|
|
}
|
|
|
|
func logColor(logger *logrus.Entry, p gin.LogFormatterParams) {
|
|
str := formatter(p)
|
|
code := p.StatusCode
|
|
switch {
|
|
case code >= http.StatusBadRequest && code < http.StatusInternalServerError:
|
|
logger.Error(str)
|
|
default:
|
|
logger.Info(str)
|
|
}
|
|
}
|
|
|
|
var formatter = func(param gin.LogFormatterParams) string {
|
|
var statusColor, methodColor, resetColor string
|
|
if param.IsOutputColor() {
|
|
statusColor = param.StatusCodeColor()
|
|
methodColor = param.MethodColor()
|
|
resetColor = param.ResetColor()
|
|
}
|
|
|
|
if param.Latency > time.Minute {
|
|
param.Latency = param.Latency.Truncate(time.Second)
|
|
}
|
|
return fmt.Sprintf("[GIN] %v |%s %3d %s| %13v | %15s |%s %-7s %s %#v\n%s",
|
|
param.TimeStamp.Format("2006/01/02 - 15:04:05"),
|
|
statusColor, param.StatusCode, resetColor,
|
|
param.Latency,
|
|
param.ClientIP,
|
|
methodColor, param.Method, resetColor,
|
|
param.Path,
|
|
param.ErrorMessage,
|
|
)
|
|
}
|