主要使用的包
package main
import (
"fmt"
"io"
"os"
"strings"
"time"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/logger"
)
退出时是否删除日志文件
const (
LOG_DELETE_FILE_ON_EXIT = false
)
不记录的路径和文件后缀名
var (
EXCLUDE_PATHS = [...]string{
HEALTH_CHECK_URL,
}
EXCLUDE_EXTENSIONS = [...]string{
".js",
".css",
".jpg",
".png",
".ico",
".svg",
}
)
logger和文件
func newRequestLogger(newWriter io.Writer) iris.Handler {
c := logger.Config{}
c.AddSkipper(func(ctx iris.Context) bool {
path := ctx.Path()
for _, p := range EXCLUDE_PATHS {
if strings.HasPrefix(path, p) {
return true
}
}
for _, ext := range EXCLUDE_EXTENSIONS {
if strings.HasSuffix(path, ext) {
return true
}
}
return false
})
c.LogFuncCtx = func(ctx iris.Context, latency time.Duration) {
datetime := time.Now().Format(ctx.Application().ConfigurationReadOnly().GetTimeFormat())
customHandlerMessage := ctx.Values().GetString("log_message")
jsonStr := fmt.Sprintf(`{"@timestamp":"%s","level":"%s","latency": "%s","ip":"%s""status": %d,"method":"%s","path":"%s","message":"%s"}`,
datetime, "INFO", latency.String(), ctx.RemoteAddr(), ctx.GetStatusCode(), ctx.Method(), ctx.Path(), customHandlerMessage)
fmt.Fprintln(newWriter, jsonStr)
}
return logger.New(c)
}
func todayFilename() string {
return fmt.Sprintf("%s.log", time.Now().Format(utility.DATE_PATTERN))
}
func newLogFile() *os.File {
path := "./logs"
filename := fmt.Sprintf("%s/%s", path, todayFilename())
if _, err := os.Stat(path); os.IsNotExist(err) {
os.Mkdir(path, 0777)
os.Chmod(path, 0777)
}
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
return f
}
main中配置logger
func main() {
app := iris.Default()
app.Use(iris.Gzip)
logFile := newLogFile()
defer func() {
logFile.Close()
if LOG_DELETE_FILE_ON_EXIT {
os.Remove(logFile.Name())
}
}()
r := newRequestLogger(logFile)
app.Use(r)
app.Listen(fmt.Sprintf(":%d", conf.Server.Port), iris.WithOptimizations, iris.WithTimeFormat(utility.DATE_TIME_PATTERN))
}
网友评论