The following code will writes gin's logs to both console and to the 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"
"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
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080