Golang base log package

Simple output

package main
import (
    "log"
)
func main() {
    log.Println("abc")
}

The output

2022/08/18 10:16:01 abc

Format: date, time, content. If you want to change the format of the output, you can set it

const (

Ldate = 1 << iota // Date

Ltime / / time

Lmicroseconds // Specifies the time with higher accuracy

Llongfile // File location and number of lines of code

Lshortfile // File name and line of code

LUTC // Set the date or time, using the UTC time zone

Lmsgprefix // Puts the prefix in front of the content, which by default is at the top of the log

LstdFlags = Ldate | Ltime / / the default value

)

For example, set the prefix

log.SetPrefix(“zhangsan:”)

zhangsan:2022/08/18 10:39:02 abc

Set the Lmsgprefix

log.SetFlags(log.Ldate | log.Lmsgprefix)

2022/08/18 zhangsan:abc

  1. Abnormal output

log.Fatal(“abc”)

The Fatal method causes the program to exit status 1

log.Panic(“abc”)

Panic indicates that the program raises a Panic exception

Set the output file

f, err := os.OpenFile("./abc.log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0664)
if err != nil {
    log.Fatal(err)
}
log.SetOutput(f)
  1. Generate log Pointers

Using default parameters

log2 := log.Default()
log2.Println("gef")

Customize new objects

func New(out io.Writer, prefix string, flag int) *Logger

The first parameter actually corresponds to the output parameter, the second is the prefix, and the third is the output format

log3 := log.New(os.Stdout, "zhangsan:", log.Ldate|log.Lmsgprefix)
log3.Println("uio")

The output

2022/08/18 zhangsan:uio

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish