Store gorm logs in a file

Viewed 466

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 Answers

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

Related