记录器写入多个文件和标准错误/标准输出

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

Logger Writing to Multiple Files & Stderr/Stdout

问题

我的目标是创建一个日志记录器,可以同时将输出发送到标准输出(info日志)和标准错误(error日志),以及相应的文件(info.log和errors.log)。

我目前在Go中使用以下方式的日志记录器:

package main

import (
    "log"
    "os"
    "io"
)

func main() {

    // 当前的方法
    infoLog := log.New("./data/info.log", "INFO\t", log.Ldate|log.Ltime)
    errorLog := log.New("./data/errors.log", "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)

    infoLog.Println("Hello INFO!")
    errorLog.Println("Hello ERROR!")

    // 我了解到可以使用io.MultiWriter来同时写入到标准输出/标准错误和一个文件中
    f, err := os.OpenFile("./data/info.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    if err != nil {
        log.Fatalf("error opening file: %v", err)
    }
    defer f.Close()
    wrt := io.MultiWriter(os.Stdout, f)
    log.SetOutput(wrt)
    log.Println("Hello World!")
}

我想要的是将infoLogerrorLog的格式(例如log.Ldate|log.Ltime)应用到io.MultiWriter中。有办法做到这一点吗?

英文:

My goal is to create a logger that I can use to output to stdout (info logs) and stderr (error logs) as well as respective files (info.log) and (errors.log) all at the same time.

I am currently using loggers in Go like the following:

package main

import (
    "log"
    "os"
    "io"
)

func main() {

    // Current method
    infoLog := log.New("./data/info.log", "INFO\t", log.Ldate|log.Ltime)
    errorLog := log.New("./data/errors.log", "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)

    infoLog.Println("Hello INFO!")
    errorLog.Println("Hello ERROR!")

    // I've read about using io.MultiWriter like the following in order to write to stdout/stderr as well as a flat file at the same time
    f, err := os.OpenFile("./data/info.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    if err != nil {
        log.Fatalf("error opening file: %v", err)
    }
    defer f.Close()
    wrt := io.MultiWriter(os.Stdout, f)
    log.SetOutput(wrt)
    log.Println("Hello World!")
}

I'd like to basically take the formatting of infoLog and errorLog (like in my first logging solution) like log.Ldate|log.Ltime and apply it to the io.MultiWriter. Is there a way to do this?

答案1

得分: 2

为了将日志信息和错误以标准格式记录在文件中,以便其他日志服务(如filebeat、logstash等)能够理解,我建议您使用github.com/sirupsen/logrus。这个包提供了SetFormatter函数来定义输出日志的格式。例如:

logrus.SetFormatter(&logrus.JSONFormatter{
		FieldMap: logrus.FieldMap{
			logrus.FieldKeyTime: "@timestamp",
			logrus.FieldKeyMsg:  "message",
			logrus.FieldKeyFunc: "func",
			logrus.FieldKeyFile: "file",
		},
	})

您可以定义用于记录日志的文件。例如:

file, err := os.OpenFile("payment_logs.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)

设置日志非常简单和标准:

logger.Info("This is an info message")
logger.Warn("This is a warning message")
logger.Error("This is an error message")

以上是要翻译的内容。

英文:

For logging info and error in file with standard format that other logging services such as filebeat, logstash and etc can understand it I suggest you to use github.com/sirupsen/logrus.
This package has SetFormater function to define format of output log. For example:

logrus.SetFormatter(&logrus.JSONFormatter{
		FieldMap: logrus.FieldMap{
			logrus.FieldKeyTime: "@timestamp",
			logrus.FieldKeyMsg:  "message",
			logrus.FieldKeyFunc: "func",
			logrus.FieldKeyFile: "file",
		},
	})

and you can define file for logging. For example:

file, err := os.OpenFile("payment_logs.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)

And set log is very easy and standard:

logger.Info("This is an info message")
logger.Warn("This is a warning message")
logger.Error("This is an error message")

huangapple
  • 本文由 发表于 2023年2月14日 02:29:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75439898.html
匿名

发表评论

匿名网友

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

确定