在Golang中,将每个日志保存在单独的行中。

huangapple go评论80阅读模式
英文:

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")

huangapple
  • 本文由 发表于 2016年1月18日 16:03:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/34849790.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定