gin 服务线上没有 systemd 日志的问题

文章目录

    原配置

    StandardOutput=append:/some_path/log/access.log
    StandardError=append:/some_path/log/err.log
    

    我确认了目录权限没有问题。

    真正的原因 systemd 版本问题

    参考

    https://unix.stackexchange.com/questions/321709/redirect-systemd-service-logs-to-file

    • systemd v236 之后支持 file
    • v240 之后支持 append。即每次重启后不会覆盖原文件

    而腾讯云上的 systemd 是旧版本的

    $ sudo systemctl --version
    systemd 237
    

    所以不支持 append。

    查看 systemd 错误日志

    journalctl -u some_service -b
    

    果然,大量的错误信息:

    Failed to parse output specifier, ignoring: /some_path/access.log

    Failed to parse output specifier

    参考:

    https://stackoverflow.com/questions/37585758/how-to-redirect-output-of-systemd-service-to-a-file/54232531#54232531

    但我还是不想浪费时间去解决垃圾腾讯云服务器的奇葩问题。
    (在阿里云同样系统上,相同的配置没有任何问题。)

    我决定,给 golang gin 加上日志文件功能。

    gin 日志文件

    https://github.com/gin-gonic/gin#how-to-write-log-file

    // Logging to a file.
    f, _ := os.Create("gin.log")
    gin.DefaultWriter = io.MultiWriter(f)
    
    // Use the following code if you need to write the logs to file and console at the same time.
    // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
    

    但用 os.Create 会造成每次重启 gin 服务,都会清空日志文件,所以优化一下:

    logFile, _ := os.OpenFile("access.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    gin.DefaultWriter = io.MultiWriter(logFile, os.Stdout)
    

    同时为了避免线上 debug 日志过多,设置:

    gin.SetMode(gin.ReleaseMode)
    

    log rotate

    Lumberjack is a Go package for writing logs to rolling files.

    https://github.com/natefinch/lumberjack

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式