如何在golang中写入.log文件?

fir*_*man 0 go

我是一个新用语言,仍然学习并需要帮助.如何将我的应用程序日志用go语言编写成类似PHP phalcon框架的".log"文件?

我搜索谷歌并获得语言教程,但没有简单的理解示例.我尝试了一些示例,但日志文本不会连续写入.这是我以前用于记录日志记录的示例,我认为这完全是错误的.

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

}
Run Code Online (Sandbox Code Playgroud)

nos*_*bee 7

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

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

}
Run Code Online (Sandbox Code Playgroud)