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 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟