Skip to content

Standard Go log package

Posted on:July 3, 2024 at 10:57 AM
Share on

When we develop a project, maybe sometimes we need to code a log package ourselves, and we can use the popular open source log project such as the standard golang log package, glog, zap which is open source project development by uber, logrus etc. So let’s dive into these packages now!

Table of contents

Open Table of contents

Youtube Video

Watch My Youtube video

Standard Go log package

It is out of the box with golang, when used it , we need create a log instance which is belong to log.Logger class. We can use the variable std which is global and defined by the Go log package itself in the folder log and the file is log.go.

log.Default().Print("use golang stardand log package std variable to print the log information")

Totally, we can create ourselves loggers using the log.New function. And we must specify function parameters. The first one is where the log information is output, which can be a file or console. The second one is the prefix of log information. Finally, the last one is the attribute of the log.

logger := log.New(os.Stderr, "[Debug]", log.Lshortfile)
logger.Print("use ourselves's logger to print the information")

About the attribute of the log, you can specify these values:

In addition to config your logger when using the New function, you can also change your logger config by using the below three methods:

The logger supplies three methods to record the different log information:

Actually, the Print method call the fmt.Sprint(v...) method, Println uses the fmt.Sprintln(v...) method and Printf call the fmt.Sprintf(format, v...) method.

package main

import (
        "log"
        "os"
)

func main() {
        // output file
        logFile, err := os.Create("./log.log")
        if err != nil {
                log.Fatalln("create file log.log failed")
        }

        defer logFile.Close()

        logger := log.New(logFile, "[Debug]", log.Lshortfile)
        logger.Print("call print line1")
        logger.SetOutput(os.Stdout)
        logger.Print("call print line2")
        logger.Println("call Println line3")

        // modify the config of the logger
        logger.SetPrefix("[Info]")
        logger.SetFlags(log.Ldate)
        logger.SetOutput(os.Stdout)
        logger.Print("Info check stdout")
}

And the output in the terminal:

go run main.go
[Debug]main.go:19: call print lien1
[Debug]main.go:20: call Println line2
[Info]2024/06/22 Info check stdout
Share on