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.

    评论

报告相同问题?