douxiji8707 2019-09-18 20:59
浏览 45

用日志包附加到当前行

I am writing a Go program and using the log package to write to a log file so that each new line will have a timestamp prepended to it. Sometimes I just want to append text to current line instead of starting a new line with the prepended timestamp.

I thought the log.Print() method would do this, as the docs say it is supposed to work the same way as fmt.Print(). Instead, I have found that each call to Print() generates a new line with a timestamp. I can't find another method in the package that does what I am looking for.

Is there a way to do this?

Example program:

logFile, err := os.Create("myLog.log")
defer logFile.Close()
logger := log.New(logFile, "", log.LstdFlags)

logger.Println("Starting first round")
for i := 1; i < 4; i++ {
    request, err := http.NewRequest("GET", "http://www.someapi.com/pgNum=" + i, nil)
    response, err := client.Do(request)
    logger.Print(".")
}

logger.Println("Starting second round")
for j := 1; j < 4; j++ {
    request, err := http.NewRequest("GET", "http://www.someotherapi.com/pgNum=" + j, nil)
    response, err := client.Do(request)
    logger.Print(".")
}

logger.Println("Done")

Current output:

2019/09/18 13:27:49 Starting first round
2019/09/18 13:27:49 .
2019/09/18 13:27:50 .
2019/09/18 13:27:51 .
2019/09/18 13:27:52 Starting second round
2019/09/18 13:27:52 .
2019/09/18 13:27:53 .
2019/09/18 13:27:54 .
2019/09/18 13:27:55 Done

Desired output:

2019/09/18 13:27:49 Starting first round...
2019/09/18 13:27:52 Starting second round...
2019/09/18 13:27:55 Done
  • 写回答

2条回答 默认 最新

  • douchenhui5569 2019-09-18 21:13
    关注

    This cannot be achived. Logging package always adds end of line character. See log.go line 169.

    The logs can be written by many routines, therefore you no have guarantee that you attach to the previously logged line.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog