How to Use the Log Interface in Go

2022年11月20日 2583点热度 0人点赞 0条评论
内容目录

Usage

Common log methods in Go:

Print/Printf/Println : Print log information
Panic/Panicf/Panicln : Print log information and call Panic with the formatted string as an argument
Fatal/Fatalf/Fatalln : Print log information and exit the program with os.Exit(1)

The definition for creating a new Logger is as follows:

func New(out io.Writer, prefix string, flag int) *Logger {
    return &Logger{out: out, prefix: prefix, flag: flag}
}

type Logger struct {
    mu     sync.Mutex // ensures atomic writes; protects the following fields
    prefix string     // prefix on each line to identify the logger (but see Lmsgprefix)
    flag   int        // properties
    out    io.Writer  // destination for output
    buf    []byte     // for accumulating text to write
}

For example, logging to a file:

package main

import (
	"fmt"
	"log"
	"os"
	"time"
)

func main() {
	fn := fmt.Sprint("log-", time.Now().Unix(), ".log")
	logFile, _ := os.Create(fn)
	defer logFile.Close()

	logger := log.New(logFile, "[Debug]", log.Ldate|log.Ltime|log.Lshortfile)
	logger.Println("test debug message")
	logger.SetPrefix("[Info]")
	logger.Println("test info message")

}

file

logger.SetPrefix("[Info]") can reset the prefix;

log.Ldate|log.Ltime|log.Lshortfile sets the flags for the log, with three enumerations in this example, allowing logs to include additional information.

Generated output: 2022/11/20 09:09:39 main.go:16

log.Ldate generates 2022/11/20;
log.Ltime generates 09:09:39;
log.Lshortfile generates main.go:16, indicating the specific location in the source code from which the log originated.

To print only to the console:

	logger := log.New(os.Stdout, "[Debug]", log.Ldate|log.Ltime|log.Lshortfile)

file

Package Log

Reference: https://www.cnblogs.com/tigerzhouv587/p/11498630.html

package main

import (
	"io"
	"io/ioutil"
	"log"
	"os"
)

var (
	Trace   *log.Logger // Record all logs
	Info    *log.Logger // Important information
	Warning *log.Logger // Information that needs attention
	Error   *log.Logger // Fatal errors
)

func init() {
	file, err := os.OpenFile("file", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalln("Failed to open error log file:", err)
	}

	Trace = log.New(ioutil.Discard, "TRACE: ", log.Ltime|log.Lshortfile)
	Info = log.New(os.Stdout, "Info: ", log.Ltime|log.Lshortfile)
	Warning = log.New(os.Stdout, "Warning: ", log.Ltime|log.Lshortfile)
	Error = log.New(io.MultiWriter(file, os.Stderr), "Error", log.Ltime|log.Lshortfile)
}

func main() {
	Trace.Println("I have something standard to say")
	Info.Println("Special Information")
	Warning.Println("There is something you need to know about")
	Error.Println("Something has failed")
}

io.MultiWriter(file, os.Stderr) allows writing to multiple IO streams simultaneously.

痴者工良

高级程序员劝退师

文章评论