Go 日志切割

知识点:

"github.com/lestrrat-go/apache-logformat"
"github.com/lestrrat-go/file-rotatelogs"

demo:package main

import (
    "log"
    "net/http"
    "time"

    apachelog "github.com/lestrrat-go/apache-logformat"
    rotatelogs "github.com/lestrrat-go/file-rotatelogs"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { })

    logf, err := rotatelogs.New(
    "/Users/zhaoxianxin/log/access_log.%Y%m%d%H%M%S",  // 设置格式 后面的 %Y%m%d%H%M%S 为年月日时分秒 sdk会自动给出
    rotatelogs.WithLinkName("/Users/zhaoxianxin/log/access_log"),  // 设置日志的软连接, 可以从这个文件查到最新的日志
    rotatelogs.WithMaxAge(15 * time.Second), // 日志的 过期时间
    rotatelogs.WithRotationTime(10 * time.Second), // 日志的 分割时间 也就是 多久创建一个新的文件 
    )
    if err != nil {
        log.Printf("failed to create rotatelogs: %s", err)
    return
    }

    // Now you must write to logf. apache-logformat library can create
    // a http.Handler that only writes the approriate logs for the request
    // to the given handle
现在你必须写入logf。apache-logformat库可以创建http。只将请求的适当日志写入给定句柄的处理程序
http.ListenAndServe(":8080", apachelog.CombinedLog.Wrap(mux, logf)) }
邮箱: 1090055252@qq.com
原文地址:https://www.cnblogs.com/zhaoxianxin/p/14489876.html