Troubleshooting Missing Logs in Golang Gin Framework

gin frameworkgolang loggingos.createlog file not createdgolang web development
Published·Modified·

Recently, a new project adopted the Golang web framework Gin. While I have used this framework before without issues, I recently encountered a strange problem: Gin was not outputting any log content (neither in the terminal nor in the log file).

Code Analysis

Here is the code:

// Start Gin
func Start() {
	// Gin default run mode
	RunMode := controller.ConfigGet("servers.RunMode")
	gin.SetMode(RunMode)

	// Log to file
	f, _ := os.Create("logs/run.log")
	gin.DefaultWriter = io.MultiWriter(f)
	// Log to both file and console
	gin.DefaultWriter = io.MultiWriter(f, os.Stdout)

	// Run Gin
	r := gin.Default()

	// Use CORS middleware
	r.Use(cors())

	// Route configuration
	r.GET("/api/check/icmp", auth(), controller.CheckIcmp)
	r.GET("/api/check/tcp", auth(), controller.CheckTcp)

	// Get server configuration
	port := controller.ConfigGet("servers.port")
	r.Run(port)
}

At first glance, the code seems correct, and there were no errors during startup. Initially, I suspected a bug in Gin, but comparing the Gin versions across other projects revealed they were identical, and the code was almost the same. I also searched online but found no similar cases.

Solution

After a long troubleshooting process, I discovered the issue lies in the line f, _ := os.Create("logs/run.log"). The os.Create() function only creates the file; if the parent directory does not exist, it will not be created automatically. Consequently, logs/run.log was not successfully created, which affected Gin's log output.

To resolve this, there are two methods:

  1. Pre-create the logs directory.
  2. Check if the log directory exists; if not, create it using the os.Mkdir() function.

Conclusion

It was my oversight. Development requires careful attention. If you encounter a similar issue where Gin does not output logs, check whether the log folder exists.