如何将日志写入文件 [英] How to write log to file
问题描述
我正在尝试使用Go写入日志文件.
I'm trying to write to a log file with Go.
我尝试了几种方法,但都失败了.这是我尝试过的:
I have tried several approaches, all of which have failed. This is what I have tried:
func TestLogging(t *testing.T) {
if !FileExists("logfile") {
CreateFile("logfile")
}
f, err := os.Open("logfile")
if err != nil {
t.Fatalf("error: %v", err)
}
// attempt #1
log.SetOutput(io.MultiWriter(os.Stderr, f))
log.Println("hello, logfile")
// attempt #2
log.SetOutput(io.Writer(f))
log.Println("hello, logfile")
// attempt #3
log.SetOutput(f)
log.Println("hello, logfile")
}
func FileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
func CreateFile(name string) error {
fo, err := os.Create(name)
if err != nil {
return err
}
defer func() {
fo.Close()
}()
return nil
}
已创建日志文件,但没有任何打印或附加的内容.为什么?
The log file gets created, but nothing ever gets printed or appended to it. Why?
推荐答案
os.Open()
过去的工作方式一定不同,但这对我有用:
os.Open()
must have worked differently in the past, but this works for me:
f, err := os.OpenFile("testlogfile", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer f.Close()
log.SetOutput(f)
log.Println("This is a test log entry")
基于Go文档,os.Open()
不适用于log.SetOutput
,因为它会打开文件供读取:"
Based on the Go docs, os.Open()
can't work for log.SetOutput
, because it opens the file "for reading:"
func Open
func Open(name string) (file *File, err error)
Open
打开命名的
文件以供阅读.如果成功,返回文件上的方法可以是
用于阅读;关联的文件描述符的模式为O_RDONLY
.如果
出现错误,它将是*PathError
类型.
func Open(name string) (file *File, err error)
Open
opens the named
file for reading. If successful, methods on the returned file can be
used for reading; the associated file descriptor has mode O_RDONLY
. If
there is an error, it will be of type *PathError
.
编辑
将defer f.Close()
移动到if err != nil
检查之后
这篇关于如何将日志写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!