Search code examples
godeferred-execution

Proper pattern to encapsulate log setup in golang


When trying to move log setup code into a separate function I ran into inability to hide the destination file object from the main function. In the following INCORRECT simplified example the attempt is made to setup log writing to both Stderr and a file via a single function call:

package main

import (
    "io"
    "log"
    "os"
)

func SetupLogging() {
    logFile, err := os.OpenFile("test.log", os.O_APPEND|os.O_CREATE, 0666)
    if err != nil {
        log.Panicln(err)
    }
    defer logFile.Close()

    log.SetOutput(io.MultiWriter(os.Stderr, logFile))
}

func main() {
    SetupLogging()
    log.Println("Test message")
}

Clearly is does not work because defer closes the log file at the end of the SetupLogging function.

A working example below adds extra code and IMHO looses some clarity if repeated in a larger application as a pattern:

package main

import (
    "io"
    "log"
    "os"
)

func SetupLogging() *os.File {
    logFile, err := os.OpenFile("test.log", os.O_APPEND|os.O_CREATE, 0666)
    if err != nil {
        log.Panicln(err)
    }

    log.SetOutput(io.MultiWriter(os.Stderr, logFile))
    return logFile
}

func main() {
    logf := SetupLogging()
    defer logf.Close()

    log.Println("Test message")
}

Is there a different way to fully encapsulate open file management into a function, yet still nicely release the handle?


Solution

  • I have now successfully used the below approach for about a year in multiple projects. The idea is to return a function from the setup call. That resulting function contains the destruction logic. Here is an example:

    package main
    
    import (
        "fmt"
        "io"
        "log"
        "os"
    )
    
    func LogSetupAndDestruct() func() {
        logFile, err := os.OpenFile("test.log", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
        if err != nil {
            log.Panicln(err)
        }
    
        log.SetOutput(io.MultiWriter(os.Stderr, logFile))
    
        return func() {
            e := logFile.Close()
            if e != nil {
                fmt.Fprintf(os.Stderr, "Problem closing the log file: %s\n", e)
            }
        }
    }
    
    func main() {
        defer LogSetupAndDestruct()()
    
        log.Println("Test message")
    }
    

    It is using a closure around the cleanup logic being deferred.

    A somewhat more elaborate public example of using this approach is in the Viper code: here is the return from a test initializer, and here it is used to encapsulate the cleanup logic and objects