英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论