如何在Golang中将日志写入.log文件?

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

How to write log into .log files in golang?

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我是一个新使用Go语言的用户,还在学习中,需要帮助。我该如何在Go语言中编写类似于PHP Phalcon框架的应用程序日志,保存为".log"文件?

我在谷歌上搜索了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")

	// 首先,这是如何将字符串(或字节)转储到文件中的示例。
	d1 := []byte("hello\ngo11\n" + dt2)
	err := ioutil.WriteFile("/Users/my/Documents/work/src/logs/log-"+dt+".log", d1, 0644)
	check(err)

	// 对于更细粒度的写入,可以打开一个文件进行写入。
	f, err := os.Create("/Users/my/Documents/work/src/logs/log1.log")
	check(err)

	// 打开文件后,立即使用`Close`进行延迟关闭是惯用的做法。
	defer f.Close()

	// 可以像预期的那样`Write`字节切片。
	d2 := []byte{115, 111, 109, 101, 10}
	n2, err := f.Write(d2)
	check(err)
	fmt.Printf("写入了 %d 个字节\n", n2)

	// 也可以使用`WriteString`。
	n3, err := f.WriteString("writes\n" + dt)
	fmt.Printf("写入了 %d 个字节\n", n3)

	// 使用`Sync`将写入刷新到稳定存储。
	f.Sync()

	// `bufio`提供了缓冲写入器,除了之前看到的缓冲读取器。
	w := bufio.NewWriter(f)
	n4, err := w.WriteString("buffered\n")
	fmt.Printf("写入了 %d 个字节\n", n4)

	// 使用`Flush`确保所有缓冲操作都已应用于底层写入器。
	w.Flush()

}

希望对你有帮助!如果你有任何其他问题,请随时提问。

英文:

I'am new use go language, still learn and need help. How can I write my application logs in go language into ".log" files similiar like PHP phalcon framework ?

I have searching google and get go language tutorials, but there is no simple understanding example. I have try some example but the logs text doesn't write continously. Here's the example that I used to learn for logging log, and I think it's completly wrong.

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

答案1

得分: 15

你试了很多不同的东西,很难确定你具体的目标是什么,但如果你只是想将日志写入文件,这里有一个示例:

package main

import (
    "log"
    "os"
)

func main() {

    // 使用所需的读写权限创建文件
    f, err := os.OpenFile("filename", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
    if err != nil {
        log.Fatal(err)
    }

    // 在使用完之后关闭文件,而不是因为你认为这是惯用的做法!
    defer f.Close()

    // 将日志输出设置为文件 f
    log.SetOutput(f)

    // 测试案例
    log.Println("检查是否正常工作")
}

希望对你有帮助!

英文:

You're trying so many different things it's hard to tell what you're aiming for specifically, but if you simply want to write logs to a file, here is an example:

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

答案2

得分: 2

我建议你看一下Lumberjack。它可以很好地处理带有多个文件条件的滚动日志。我正在将其用于流式网络传感器。

英文:

I recommend taking a look at Lumberjack. It handles rolling logs with several file conditions quite nicely. I'm using it for a streaming network sensor.

答案3

得分: 2

我有一个使用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

}
英文:

I have a small project that uses the log.Logger as following:

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

}

答案4

得分: 1

import (
"os/exec"
)

func main() {
// 在这里检查错误...
exec.Command("/bin/sh", "-c", "echo "+err.Error()+" >> log.log").Run()
}

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

答案5

得分: 0

我有一个记录器来执行这个操作,这里是一个示例。
Send message 将错误发送到我的 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))
// 当周围的函数退出时关闭文件
defer file.Close()
}
return n, err
}
// Logger 是一个辅助方法,用于打印更有用的错误消息
var Logger = log.New(errorLog{}, "", log.Lmicroseconds|log.Lshortfile)
英文:

I have my logger do this, here is an example.
Send message sends error to my IRC and sendSMS sends error to my phone.
in my config file I have:

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)

huangapple
  • 本文由 发表于 2016年11月6日 06:25:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/40443881.html
匿名

发表评论

匿名网友

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

确定