Go 为什么log.Println(“不登录文件”)?
这是我第一次尝试使用golang登录文件Go 为什么log.Println(“不登录文件”)?,go,Go,这是我第一次尝试使用golang登录文件 file, _ := os.Open("logfile") log.SetOutput(file) log.Println("foo") 这些线路已建立,但不起作用。为什么? file,err:=os.Open(“file.go”)//用于读取访问。 如果出错!=零{ //做点什么 } //并尝试包含文件路径… 为什么log.Println(“不登录文件”) 原因是您没有检查该文件是否存在或是否构成代码 file, _ := os.Open("logf
file, _ := os.Open("logfile")
log.SetOutput(file)
log.Println("foo")
这些线路已建立,但不起作用。为什么?
file,err:=os.Open(“file.go”)//用于读取访问。
如果出错!=零{
//做点什么
}
//并尝试包含文件路径…
为什么log.Println(“不登录文件”)
原因是您没有检查该文件是否存在或是否构成代码
file, _ := os.Open("logfile")
您正在使用\u
,但未检查错误。如果您想在文件中写入某些内容,这一点很重要。例如,请看以下代码:
f, err := os.OpenFile(filePath+fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModePerm)
if err != nil {
// if error then you need to create the file first
err = os.MkdirAll(filePath, os.ModePerm)
}
从上面的代码中,您可以看到使用if err!=无
。如果该文件尚不存在,则首先创建该文件。使用os.MkdirAll()。如果文件不存在,则没有创建文件的标志。因此,您需要使用O_CREATE标志调用OpenFile。我已注释掉错误代码:
package main
import (
"log"
"os"
"syscall"
)
const (
O_RDONLY int = syscall.O_RDONLY // open the file read-only.
O_RDWR int = syscall.O_RDWR // open the file read-write.
O_CREATE int = syscall.O_CREAT // create a new file if none exists.
O_APPEND int = syscall.O_APPEND // append data to the file when writing.
)
func main() {
/*f1, err := os.OpenFile("testlogfile1", O_RDONLY, 0) // Equivalent to os.Open("testlogfile1")
if err != nil {
log.Fatalf("error opening file1: %v", err)
}
// ** error opening file: open testlogfile1: no such file or directory exit status 1 **
defer f1.Close()
log.SetOutput(f1)
log.Println("This is a test for log 1")*/
f2, err := os.OpenFile("testlogfile2", O_RDWR | O_CREATE | O_APPEND, 0644)
/* Note that you want:
* O_RDWR to write to the file
* O_CREATE to create file if it does not exist
* O_APPEND to add additional information to existing file */
if err != nil {
log.Fatalf("error opening file2: %v", err)
}
defer f2.Close()
log.SetOutput(f2)
log.Println("This is a test for log 2")
}
总是检查那些错误 您正在忽略错误,然后询问代码为什么不能按预期工作?它应该是return createLogFile(前缀、文件路径、文件名)
。另外,如果由于某种原因路径存在,但文件不可访问(缺乏权限)@zerkms-ahh我看你是对的,那么这将是一个无限循环。谢谢你指出。