Gin web framework in Golang does not output log issue

Publish: 2022-11-28 | Modify: 2022-11-28

Recently, a new project used the Golang web framework Gin. I have used this framework before and it worked well. However, I recently encountered a strange issue where Gin did not output any log content (including in the terminal and log files).

Code Analysis

Here is the code:

// Start Gin
func Start() {
    // Set Gin 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 console as well
    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, there doesn't seem to be any problem with this code, and there are no errors when starting it. I initially thought it was a bug in Gin, but comparing it with other projects using the same version of Gin, the code is almost identical. I also couldn't find similar cases online.

Problem Solution

After a long time of debugging, I found that the issue was caused by the line f, _ := os.Create("logs/run.log"). os.Create() only creates the file, and if the parent directory does not exist, it will not automatically create the directory. This resulted in the logs/run.log file not being created successfully, which affected the log output of the Gin framework.

To solve this problem, there are two options:

  1. Pre-create the logs directory for the logs.
  2. Or, check if the log directory exists first and create it using the os.Mkdir() function if it doesn't.

Conclusion

It's my own carelessness. Development requires carefulness and rigor. If you also encounter a similar issue where Gin does not output logs, you might want to check if it is because the log directory does not exist.


Comments