The following code will writes both gin's logs and logs from log/slog into a single file. The example also uses lumberjack to implement the log rotation mechanism.
NOTE: When using this configuration the console logs will not show colors
package main
import (
"io"
"log/slog"
"os"
"github.com/gin-gonic/gin"
"gopkg.in/natefinch/lumberjack.v2"
)
func main() {
// Configure lumberjack for log rotation
logFile := &lumberjack.Logger{
Filename: "app.log",
MaxSize: 10, // MB
MaxBackups: 5,
MaxAge: 28, // days
Compress: true, // compress rotated files
}
// Create a multi-writer to write to both stdout and the log file
multiWriter := io.MultiWriter(os.Stdout, logFile)
gin.DefaultWriter = multiWriter // Sets the writer for Gin's logger
gin.DefaultErrorWriter = multiWriter // If you also want to log recovery (panic) to the file
// Re-using the io.Writer to write the logs from log/slog into the same app.log file that gin's logger also uses
logger := slog.New(slog.NewTextHandler(multiWriter, &slog.HandlerOptions{}))
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
logger.Debug("Debug")
logger.Info("Info")
logger.Warn("Warn")
logger.Error("Error")
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}