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

时间:2016-11-05 22:25:13

标签: go

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

我已经搜索谷歌并获得语言教程,但没有简单的理解示例。我尝试了一些例子,但是日志文本不能连续写入。这是我以前学习记录日志的例子,我认为它完全错了。

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

}

5 个答案:

答案 0 :(得分: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")

}

答案 1 :(得分:1)

我建议您查看Lumberjack。它可以很好地处理具有多个文件条件的滚动日志。我将它用于流媒体网络传感器。

答案 2 :(得分:1)

import (
    "os/exec"
)

func main() {
    // check error here...
    exec.Command("/bin/sh", "-c", "echo "+err.Error()+" >> log.log").Run()
}

答案 3 :(得分:0)

我有我的记录器这样做,这是一个例子。 发送消息发送错误到我的IRC和sendSMS发送错误到我的手机。 在我的配置文件中我有:

var ErrorFile = "error.log"

type errorLog struct {
}

func (e errorLog) Write(p []byte) (n int, err error) {
fmt.Println("Error: " + string(p))
if config.Verbose == 0 {
    file, _ := os.OpenFile(config.ErrorFile, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
    file.WriteString(string(p))
    sendMSG(string(p))
    sendSMS(string(p))
    // Close the file when the surrounding function exists
    defer file.Close()
}

   return n, err
}

// Logger is a helpper method to print out a more useful error message
var Logger = log.New(errorLog{}, "", log.Lmicroseconds|log.Lshortfile)

答案 4 :(得分:0)

我有一个使用 log.Logger 的小项目,如下所示:

package main

import (
    "errors"
    "log"
    "os"
)

const (
    logNone     = iota
    logInfo
    logWarning
    logError
    logVerbose
    logDebug
)

type myFileLogger struct {
    logger       *log.Logger
    logFile      *os.File
    logLevel     int
}

func newFileLogger() *myFileLogger {
    return &myFileLogger{
        logger:   nil,
        logFile:  nil,
        logLevel: logNone,
    }
}

func (myLogger *myFileLogger) startLog(level int, file string) error {
    f, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_APPEND, os.ModePerm)
    if err != nil {
        return err
    }
    myLogger.logger = log.New(f, "", 0)
    myLogger.logLevel = level
    myLogger.logFile = f
    return nil
}
func (myLogger *myFileLogger) stopLog() error {
    if myLogger.logFile != nil {
        return myLogger.logFile.Close()
    }
    return nil
}
// You can add a log of auxiliary functions here to make the log more easier
func (myLogger *myFileLogger) log(level int, msg string) error {
    if myLogger.logger == nil {
        return errors.New("myFileLogger is not initialized correctly")
    }
    if level >= myLogger.logLevel {
        myLogger.logger.Print(msg) // maybe you want to include the loglevel here, modify it as you want
    }
    return nil
}

func main() {

    logger := newFileLogger()
    if err := logger.startLog(logError, "myLogFile.log"); err != nil {
        panic(err.Error())
    }

    defer func() {
        logger.stopLog()
    }()

    logger.log(logInfo, "Info level log msg\n") // this will be ignored
    logger.log(logError, "Error: error message\n") // this should included in the log file

}