How to write multiple lines into a text file using golang

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

How to write multiple lines into a text file using golang

问题

我正在尝试将错误写入文本文件。然而,我似乎无法弄清楚为什么它不会打印多个错误。它只会打印最新的错误。

        for {
            if resp.StatusCode == 200 {
                ...   
			    break
            } else {
                data := fmt.Sprintf("[" + time.Now().Format("15:04:05") + "] " + strconv.Itoa(resp.StatusCode) + string(body) + "\n")
				file, err := os.Open("assets/errors.txt")
				if err != nil {
					fmt.Println(err)
				}

				write := bufio.NewWriter(file)
				write.WriteString(data)
				write.Flush()
            }
英文:

I'm trying to write errors into a text file. However, I can't seem to figure out why it's not printing multiple errors. It just prints the latest one.

        for {
            if resp.StatusCode == 200 {
                ...   
			    break
            } else {
                data := fmt.Sprintf("[" + time.Now().Format("15:04:05") +"] " + strconv.Itoa(resp.StatusCode) + string(body) + "\n")
				file, err := os.Open("assets/errors.txt")
				if err != nil {
					fmt.Println(err)
				}

				write := bufio.NewWriter(file)
				write.WriteString(data)
				write.Flush()
            }

答案1

得分: 1

我建议你创建一个函数来实现这个功能,就像这样简单的代码:

func LogErrors(errors []error, filePath string) error {
	f, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)

	if err != nil {
		return err
	}

	writer := bufio.NewWriter(f)

	for _, e := range errors {
		writer.WriteString(e.Error())
		writer.WriteString("\n")
	}

	writer.Flush()
	return nil
}

你可以像这样使用它:

func main() {
	t := time.Now()
	filePath := fmt.Sprintf("/tmp/log-%s", t.Format("2006-01-02_15_04_05"))

	es := []error{
		errors.New("something is bad"),
		errors.New("another error fix it"),
	}
	LogErrors(es, filePath)
}
英文:

I would like suggest you creating a function for that, as simple like:


func LogErrors(errors []error, filePath string) error {
	f, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)

	if err != nil {
		return err
	}

	writer := bufio.NewWriter(f)

	for _, e := range errors {
		writer.WriteString(e.Error())
		writer.WriteString("\n")
	}

	writer.Flush()
	return nil
}

And you can use it like:


func main() {
	t := time.Now()
	filePath := fmt.Sprintf("/tmp/log-%s", t.Format("2006-01-02_15_04_05"))

	es := []error{
		errors.New("something is bad"),
		errors.New("another error fix it"),
	}
	LogErrors(es, filePath)
}

huangapple
  • 本文由 发表于 2021年12月30日 04:57:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/70524937.html
匿名

发表评论

匿名网友

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

确定