将gorm日志存储到文件中。

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

Store gorm logs in a file

问题

我想将gorm的日志存储到文件中,但是我找不到任何示例或文档。我该如何实现这个目标?

英文:

I would like to store the gorm logs in a file. However I could not find any example or documentation for that. How can I accomplish that?

答案1

得分: 4

你可以将*gorm.Config值传递给gorm.Open()(它实现了gorm.Option),在其中可以指定自定义日志记录器。

你可以使用logger.New()创建自己的日志记录器,它允许你传递一个负责记录消息的logger.Writer,例如可以将日志记录到文件中。

请注意,logger.Writer是一个接口,由标准库的log.Logger实现。你可以使用log.New()创建一个指向文件的标准库日志记录器。

将这些部分组合起来:

file, err := os.Create("gorm-log.txt")
if err != nil {
    // 处理错误
    panic(err)
}
// 确保在应用程序关闭之前关闭文件。

fileLogger := logger.New(file, "", log.LstdFlags)

db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
  Logger: fileLogger,
})

上面的示例将使用fileLogger替换默认的日志记录器,它只会将日志记录到文件中。如果你想同时将日志记录到控制台(标准输出)和文件中,可以使用io.MultiWriter()创建一个io.Writer,它会同时写入标准输出和文件:

file, err := os.Create("gorm-log.txt")
if err != nil {
    // 处理错误
    panic(err)
}
// 确保在应用程序关闭之前关闭文件。

multiOutput := io.MultiWriter(os.Stdout, file)

multiLogger := logger.New(multiOutput, "", log.LstdFlags)

db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
  Logger: multiLogger,
})

在这里阅读更多关于gorm日志记录的信息:https://gorm.io/docs/logger.html

英文:

You may pass a *gorm.Config value to gorm.Open() (it implements gorm.Option) where you may specify a custom logger.

You may create your logger using logger.New() which allows you to pass a logger.Writer that is responsible to log messages, which may log to a file for example.

Note that logger.Writer is an interface that is implemented by the standard library's log.Logger. You may create a standard library's logger directed to a file using log.New().

Putting the pieces together:

file, err := os.Create("gorm-log.txt")
if err != nil {
    // Handle error
    panic(err)
}
// Make sure file is closed before your app shuts down.

fileLogger := logger.New(file, "", log.LstdFlags)

db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
  Logger: fileLogger,
})

The above example will replace the default logger with fileLogger which will log only to file. If you want to log both to your console (standard output) and to a file, you may use io.MultiWriter() to create an io.Writer that writes to both the standard output and to a file:

file, err := os.Create("gorm-log.txt")
if err != nil {
    // Handle error
    panic(err)
}
// Make sure file is closed before your app shuts down.

multiOutput := io.MultiWriter(os.Stdout, file)

multiLogger := logger.New(multiOutput, "", log.LstdFlags)

db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
  Logger: multiLogger,
})

Read more about gorm logging here: https://gorm.io/docs/logger.html

huangapple
  • 本文由 发表于 2021年10月22日 15:39:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/69673048.html
匿名

发表评论

匿名网友

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

确定