为什么log.Println(“不会记录到文件”)?

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

Why log.Println("does not log into file")?

问题

这是我第一次尝试使用Golang记录文件。

file, _ := os.Open("logfile")
log.SetOutput(file)
log.Println("foo")

这些代码段可以编译通过,但是为什么没有起作用呢?

英文:

This is my first attempt to log into files with golang.

file, _ := os.Open("logfile")
log.SetOutput(file)
log.Println("foo")

these lines build, but are not working. Why?

答案1

得分: 6

os.Open调用OpenFile(name, O_RDONLY, 0)。这里没有使用O_CREATE标志来创建文件,如果文件不存在的话。因此,你需要使用带有O_CREATE标志的OpenFile。我已经注释掉了错误代码:

package main

import (
	"log"
	"os"
	"syscall"
)

const (
	O_RDONLY int = syscall.O_RDONLY // 只读方式打开文件。
    O_RDWR   int = syscall.O_RDWR   // 读写方式打开文件。
	O_CREATE int = syscall.O_CREAT  // 如果文件不存在,则创建一个新文件。
    O_APPEND int = syscall.O_APPEND // 写入时追加数据到文件末尾。
)

func main() {
	/*f1, err := os.OpenFile("testlogfile1", O_RDONLY, 0) // 等同于 os.Open("testlogfile1")
	if err != nil {
		log.Fatalf("打开文件1时发生错误:%v", err)
	}
	// ** 打开文件错误:打开 testlogfile1: 没有那个文件或目录 退出状态 1 **

	defer f1.Close()

	log.SetOutput(f1)
	log.Println("这是一个日志测试1")*/

	f2, err := os.OpenFile("testlogfile2", O_RDWR | O_CREATE | O_APPEND, 0644)
    /* 注意你需要:
     * O_RDWR 以写入方式打开文件
     * O_CREATE 如果文件不存在,则创建文件
     * O_APPEND 在写入时追加到现有文件中的附加信息 */

	if err != nil {
		log.Fatalf("打开文件2时发生错误:%v", err)
	}

	defer f2.Close()

	log.SetOutput(f2)
	log.Println("这是一个日志测试2")

}

始终检查这些错误

[1]: https://golang.org/src/os/file.go?s=7374:7411#L236
英文:

os.Open calls OpenFile(name, O_RDONLY, 0). This does not have the flag O_CREATE to create the file if it does not exist. Therefore you need to call OpenFile with the O_CREATE flag. I have commented out the error code:

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

}

Always check those errors!

答案2

得分: 3

为什么log.Println("does not log into file")不会将日志记录到文件中?

原因是你的代码没有检查文件是否存在。

file, _ := os.Open("logfile")

你使用了_并且没有检查错误。如果你想要将内容写入文件中,这一点非常重要。例如,看看下面的代码:

f, err := os.OpenFile(filePath+fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModePerm)
if err != nil {
    // 如果出现错误,则需要先创建文件
    err = os.MkdirAll(filePath, os.ModePerm)
}

从上面的代码中可以看到使用了if err != nil进行错误检查。如果文件尚不存在,则先创建文件,使用os.MkdirAll()

英文:

> Why log.Println(“does not log into file”)?

The reason is because you didn't check the file is exist or not form your code.

file, _ := os.Open("logfile")

you're using _ and didn't check the error. This is important if you wanted to write something in to file. For example look at this code :

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

from above code you can see the error checking using if err != nil. if the file is not exist yet then create the file first. using os.MkdirAll().

答案3

得分: -1

文件错误 := os.Open("file.go") // 用于读取访问。
if 错误 != nil {
    // 做一些事情
}

// 并尝试包含文件路径...
英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

file, err := os.Open(&quot;file.go&quot;) // For read access.
if err != nil {
	// do something
}

// and try to include the file path...

<!-- end snippet -->

huangapple
  • 本文由 发表于 2017年3月17日 15:02:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/42851179.html
匿名

发表评论

匿名网友

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

确定