Skip to content

Instantly share code, notes, and snippets.

@tysonpaul89
Created November 5, 2024 18:26
Show Gist options
  • Select an option

  • Save tysonpaul89/101e644850c607ed1284ef8e16632d88 to your computer and use it in GitHub Desktop.

Select an option

Save tysonpaul89/101e644850c607ed1284ef8e16632d88 to your computer and use it in GitHub Desktop.
How to log gin's logs to file and console

Gin Log to file

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment