英文:
Save each log in a separate line in Golang
问题
我尝试为我的代码添加日志,但无法使每个日志单独显示在一行上。
这是我的代码:
package main
import (
"log"
"os"
)
func update() {
log.Println(1, "update")
log.Println(1, "update")
log.Println(1, "update")
log.Println(1, "update")
}
func install() {
log.Println(1, "install")
log.Println(1, "install")
log.Println(1, "install")
log.Println(1, "install")
}
func main() {
// 确保 log.txt 文件存在
// 如果 log.txt 不存在,使用 touch 命令创建
os.Create("log/Installationlog.txt")
logFile, err := os.OpenFile("log/Installationlog.txt", os.O_WRONLY, 0666)
if err != nil {
panic(err)
}
defer logFile.Close()
// 将所有日志消息定向到 log.txt
log.SetOutput(logFile)
log.Println("ERROR::First log message!")
install()
update()
}
我的代码的输出是:
2016/01/18 13:30:51 ERROR::First log message! 2016/01/18 13:30:51 1 install 2016/01/18 13:30:51 1 install 2016/01/18 13:30:51 1 install 2016/01/18 13:30:51 1 install 2016/01/18 13:30:51 1 update 2016/01/18 13:30:51 1 update 2016/01/18 13:30:51 1 update 2016/01/18 13:30:51 1 update
所有内容都在一行上,我希望它们每个都在单独的行上。
提前感谢。
英文:
I tried to add log for my code but i couldn't get each log on a separate line
This is my code
package main
import (
"log"
"os"
)
func update(){
log.Println(1,"update")
log.Println(1,"update")
log.Println(1,"update")
log.Println(1,"update")
}
func install(){
log.Println(1,"install")
log.Println(1,"install")
log.Println(1,"install")
log.Println(1,"install")
}
func main() {
// make sure log.txt exists first
// use touch command to create if log.txt does not exist
os.Create("log/Installationlog.txt")
logFile, err := os.OpenFile("log/Installationlog.txt", os.O_WRONLY, 0666)
if err != nil {
panic(err)
}
defer logFile.Close()
// direct all log messages to log.txt
log.SetOutput(logFile)
log.Println("ERROR::First log message!")
install()
update()
}
The output of my code is
2016/01/18 13:30:51 ERROR::First log message! 2016/01/18 13:30:51 1 install 2016/01/18 13:30:51 1 install 2016/01/18 13:30:51 1 install 2016/01/18 13:30:51 1 install 2016/01/18 13:30:51 1 update 2016/01/18 13:30:51 1 update 2016/01/18 13:30:51 1 update 2016/01/18 13:30:51 1 update
All in a single line i want each of them to be in separate line
Thanks in Advance
答案1
得分: 1
也许这段代码可以帮助你("\n" -> "\n\r")("\n\r"的作用与"\r\n"相同):
log.SetPrefix("\r")
英文:
Maybe This code will help u ("\n" -> "\n\r")("\n\r" works same as "\r\n"):
log.SetPrefix("\r")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论