download2014711 2019-03-13 18:48
浏览 94
已采纳

Golang:如何在自定义文件中记录fmt.Printf

I have this function which I use to log:

func formattedLog(prefix, m string, color int) {
    fmt.Printf("\033[%dm%s", color, DateTimeFormat)
    fmt.Printf("▶ %s: %s\033[%dm
", prefix, m, int(Black))
}

I want to save my log output in some file:

f, err := os.OpenFile("../../../go-logs.txt", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
    log.Fatal("error opening logs file", err)
}
defer f.Close()
//set output of logs to f
log.SetOutput(f)
log.Println("This is a test log entry") // <====This logs in file

but when I call my function, which uses fmt.Printf it doesn't log in the file go-logs.txt:

formattedErr("ERR", msg, err.Error(), int(Red))

is there anyway to setoutput also for fmt.Printf

  • 写回答

1条回答 默认 最新

  • dongshuo1856 2019-03-13 18:53
    关注

    fmt.Printf() documents that it writes to the standard output:

    Printf formats according to a format specifier and writes to standard output.

    So there is no fmt.SetOutput() to redirect that to your file.

    But note that the standard output is a variable in the os package:

    Stdin, Stdout, and Stderr are open Files pointing to the standard input, standard output, and standard error file descriptors.

    Note that the Go runtime writes to standard error for panics and crashes; closing Stderr may cause those messages to go elsewhere, perhaps to a file opened later.

    var (
            Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
            Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
            Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
    )
    

    And you are allowed to set your own os.File to os.Stdout. Although it's not a good idea to use the same os.File for a logger and to also set it to os.Stdout, access to its File.Write() method would not be synchronized between the fmt package and the logger.

    Best would be to use a log.Logger everywhere (whose output you properly set, so log messages would properly be serialized).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)