dpbsy60000 2014-08-16 18:47
浏览 204
已采纳

在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?

  • 写回答

4条回答 默认 最新

  • duannian3494 2015-09-09 00:36
    关注

    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
    ", 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里