普通网友 2019-07-25 05:54
浏览 46
已采纳

关闭延迟关闭的文件

In my main function, I open a logging text file for writing with a defer close method to close it once the application quits. However, at the beginning of each new day I wish to start writing to the next day's log file, and I don't know how to close the previous day's file and start writing to the current one.

In my main function:

func main() {

f, err := os.OpenFile("2019-07-24.txt", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0644)
    if err != nil {
        log.Fatalf("Error opening log file: %v", err)
    }
    defer f.Close()

    log.SetOutput(f)

}

Now when I receive a message on a new day in another package:

func gateway() {

f, err := os.OpenFile("2019-07-25.txt", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0644)
    if err != nil {
        log.Fatalf("Error opening log file: %v", err)
    }
    defer f.Close()

    log.SetOutput(f)

}

How do I get a pointer to the previous day's log file from another package, and then close it (when a defer call will not be invoked unless the application completely closes?

  • 写回答

1条回答 默认 最新

  • donglao7947 2019-07-25 06:13
    关注

    Create a package that that manages the log output.

    package logoutput
    
    package main
    
    import (
        "io"
        "log"
        "sync"
    )
    
    var (
        mu            sync.Mutex
        curr io.WriteCloser
    )
    
    func Set(w io.WriteCloser) {
        mu.Lock()
        defer mu.Unlock()
        prev := curr
        curr = w
        log.SetOutput(curr)
        if prev != nil {
           prev.Close()
        }
    }
    
    func Close() {
        mu.Lock()
        defer mu.Unlock()
        log.SetOutput(os.Stderr) // revert to default
        if curr != nil {
           curr.Close()
        }
        curr = nil
    }
    

    Call the package from main and the gateway package.

    f, err := os.OpenFile("2019-07-24.txt", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0644)
    if err != nil {
        log.Fatalf("Error opening log file: %v", err)
    }
    logoutput.Set(f)
    defer logoutput.Close() // call from main only
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答