每日日志轮转的Golang项目

huangapple go评论95阅读模式
英文:

Daily Log Rotation for Golang Project

问题

我正在使用 logrus 包进行日志记录。希望能够每天轮转日志。

我已经探索了一些选项,比如 lumberjacklogrotate(8)

但是 lumberjack 基于日志文件的大小进行日志轮转。不确定是否有办法使其每天轮转日志。

对于 logrotate,我需要在系统级别创建一个单独的配置文件,但我希望避免这样做,因为这样我就需要处理两个不同的事情,并且可扩展性会成为一个问题。不确定如何只通过在项目级别创建配置文件或其他更好的方法来使用它。

所以,在 Golang 中有没有办法每天进行日志轮转呢?

英文:

I am using logrus package for logging. Want to rotate the logs on daily basis.

I have explored options like lumberjack and logrotate(8)

But lumberjack provides log rotation based on the size of the log file. Not sure if there is any way to make it rotate logs on daily basis.

For logrotate, I will have to create a separate config at the system level which I want to avoid as will have to look after two different things and scalability will an issue. Not sure how we can use this just by creating config at the project level or some other better approach.

So is there any way to do log rotating on a daily basis in Golang?

答案1

得分: 2

你可以尝试来自Krzysztof Kowalczyk的kjk/dailyrotate,它是一个名为"dailyrotate"的Go库,用于实现日志轮转。

默认情况下,日志每天在UTC时间午夜进行轮转。

var (
	logFile *dailyrotate.File
)

func openLogFile(pathFormat string, onClose func(string, bool)) error {
	w, err := dailyrotate.NewFile(pathFormat, onLogClose)
	if err != nil {
		return err
	}
	logFile = w
	return nil
}

func main() {
	logDir := "logs"

	// 我们必须确保要写入的目录已经存在
	err := os.MkdirAll(logDir, 0755)
	if err != nil {
		log.Fatalf("os.MkdirAll()失败:%s", err)
	}

	pathFormat := filepath.Join(logDir, "2006-01-02.txt")
	err = openLogFile(pathFormat, onLogClose)
	if err != nil {
		log.Fatalf("openLogFile失败:%s\n", err)
	}

  // ... 程序的其余部分
}
英文:

You can try kjk/dailyrotate from Krzysztof Kowalczyk, presented in "What is dailyrotate?"

> dailyrotate is a Go library that makes it easy to implement log rotation.
By defaultd logs rotate daily, at midnight UTC time.

var (
	logFile *dailyrotate.File
)

func openLogFile(pathFormat string, onClose func(string, bool)) error {
	w, err := dailyrotate.NewFile(pathFormat, onLogClose)
	if err != nil {
		return err
	}
	logFile = w
	return nil
}

func main() {
	logDir := "logs"

	// we have to ensure the directory we want to write to
	// already exists
	err := os.MkdirAll(logDir, 0755)
	if err != nil {
		log.Fatalf("os.MkdirAll()(")
	}

	pathFormat := filepath.Join(logDir, "2006-01-02.txt")
	err = openLogFile(pathFormat, onLogClose)
	if err != nil {
		log.Fatalf("openLogFile failed with '%s'\n", err)
	}

  // ... the rest of your program
}

huangapple
  • 本文由 发表于 2021年11月25日 14:48:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/70106874.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定