Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save tysonpaul89/b04e472abe37504a623bda0b189d69b0 to your computer and use it in GitHub Desktop.
To log Gin's and log/slog logs to same file

Gin Log and log/slog log to the same file

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