gpt4 book ai didi

go - 如何将日志写入 golang 中的 .log 文件?

转载 作者:IT王子 更新时间:2023-10-29 02:25:22 24 4
gpt4 key购买 nike

我是 go 语言的新手,仍在学习并需要帮助。如何将我的应用程序日志用 go 语言写入类似于 PHP phalcon 框架的“.log”文件?

我搜索了google和get go语言教程,但是没有简单理解的例子。我尝试了一些示例,但日志文本没有连续写入。这是我用来学习记录日志的例子,我认为这是完全错误的。

package main

import (
"bufio"
"fmt"
"io/ioutil"
"os"
"time"
)

func check(e error) {
if e != nil {
panic(e)
}
}



func main() {

now := time.Now()
dt := now.Format("2006-01-02")

dt2 := now.Format("2006-01-02 15:04:05")

// To start, here's how to dump a string (or just
// bytes) into a file.
d1 := []byte("hello\ngo11\n" + dt2)
err := ioutil.WriteFile("/Users/my/Documents/work/src/logs/log-"+dt+".log", d1, 0644)
check(err)

// For more granular writes, open a file for writing.
f, err := os.Create("/Users/my/Documents/work/src/logs/log1.log")
check(err)

// It's idiomatic to defer a `Close` immediately
// after opening a file.
defer f.Close()

// You can `Write` byte slices as you'd expect.
d2 := []byte{115, 111, 109, 101, 10}
n2, err := f.Write(d2)
check(err)
fmt.Printf("wrote %d bytes\n", n2)

// A `WriteString` is also available.
n3, err := f.WriteString("writes\n" + dt)
fmt.Printf("wrote %d bytes\n", n3)

// Issue a `Sync` to flush writes to stable storage.
f.Sync()

// `bufio` provides buffered writers in addition
// to the buffered readers we saw earlier.
w := bufio.NewWriter(f)
n4, err := w.WriteString("buffered\n")
fmt.Printf("wrote %d bytes\n", n4)

// Use `Flush` to ensure all buffered operations have
// been applied to the underlying writer.
w.Flush()

}

最佳答案

你正在尝试很多不同的事情,很难说出你的具体目标是什么,但如果你只是想将日志写入文件,这里有一个例子:

package main

import (
"log"
"os"
)

func main() {

//create your file with desired read/write permissions
f, err := os.OpenFile("filename", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatal(err)
}

//defer to close when you're done with it, not because you think it's idiomatic!
defer f.Close()

//set output of logs to f
log.SetOutput(f)

//test case
log.Println("check to make sure it works")

}

关于go - 如何将日志写入 golang 中的 .log 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40443881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com