在 Linux 上使用 Golang 进行日志管理,你可以遵循以下步骤:
选择合适的日志库:Golang 标准库提供了基本的日志功能,但可能不足以满足你的需求。因此,你可以选择一个更强大的第三方日志库,如 logrus、zap 或 zerolog。
安装日志库:以 logrus 为例,你可以使用以下命令安装:
go get github.com/sirupsen/logrus
import (
log "github.com/sirupsen/logrus"
)
func init() {
log.SetFormatter(&log.JSONFormatter{})
file, err := os.OpenFile("logs/app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err == nil {
log.Out = file
} else {
log.Info("Failed to log to file, using default stderr")
}
}
log.Debug("This is a debug message")
log.Info("This is an info message")
log.Warn("This is a warning message")
log.Error("This is an error message")
logrotate.conf 的配置文件,并添加以下内容:/path/to/your/logs/app.log {
daily
rotate 7
compress
missingok
notifempty
create 0640 root root
}
这个配置表示每天轮转日志文件,保留最近 7 天的日志,并对旧日志进行压缩。
/etc/cron.daily/logrotate 文件中,以便每天运行 logrotate:#!/bin/sh
/usr/sbin/logrotate /etc/logrotate.conf
确保该文件具有可执行权限:
chmod +x /etc/cron.daily/logrotate
现在,你的 Golang 应用程序将在 Linux 上使用 logrus 进行日志管理,并利用 logrotate 进行日志轮转。你可以根据需要调整配置以满足你的需求。