douqiang6036 2019-02-22 05:05
浏览 773

如何在golang中将日志写入多个日志文件?

I am writing an application in which i need to record logs in two different files. For Example weblogs.go and debuglogs.go. I tried using the log4go but my requirement is i need the logger to be created in main file and be accessible in sub directory as major of decoding and logging is done in sub file. Can anybody please help with that?

  • 写回答

1条回答 默认 最新

  • duangou1953 2019-02-22 13:40
    关注

    Here's one way to do it, using the standard log package:

    package main
    
    import (
        "io"
        "log"
        "os"
    )
    
    func main() {
        f1, err := os.Create("/tmp/file1")
        if err != nil {
            panic(err)
        }
        defer f1.Close()
    
        f2, err := os.Create("/tmp/file2")
        if err != nil {
            panic(err)
        }
        defer f2.Close()
    
        w := io.MultiWriter(os.Stdout, f1, f2)
        logger := log.New(w, "logger", log.LstdFlags)
    
        myfunc(logger)
    }
    
    func myfunc(logger *log.Logger) {
        logger.Print("Hello, log file!!")
    }
    

    Notes:

    1. io.MultiWriter is used to combine several writers together. Here, it creates a writer w - a write to w will go to os.Stdout as well as two files
    2. log.New lets us create a new log.Logger object with a custom writer
    3. The log.Logger object can be passed around to functions and used by them to log things
    评论

报告相同问题?

悬赏问题

  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn