SoFunction
Updated on 2025-03-03

Detailed explanation of the log package example in go language

Go languagelogPackage provides basic functions for logging. compared tofmtBag,logThe package adds log management functions such as timestamps and log levels, which are very suitable for debugging and recording operational information. The following is the rightlogThe detailed description of the package, and it withfmtThe difference between packages.

1. Basic functions of log package

logThe package contains a series of functions that can be used to print timestamped log information, and the logs are written to standard error output by default () and add a timestamp at the beginning of each log.

Common functions

: Basic log output function, similar to, but timestamp will be added before output.

: Similar to, a timestamp will be added before the output and a newline will be added at the end.

: Similar to, supports formatting output and adds a timestamp before output.

Sample code:

package main
import "log"
func main() {
    ("This is a log message.")
    ("This is another log message.")
    ("Formatted log: %d + %d = %d", 2, 3, 2+3)
}

2. Log level function of log package

logThe package also provides two special logging functions for handling errors and program exits:

: Used to record serious error information, it will be called after outputting the log(1), terminate the program execution.

: Used to record error information and callpanic, causing panic (program crashes and throws stack information), suitable for debugging and handling abnormal situations.

Sample code:

package main
import "log"
func main() {
    ("This is a normal log.")
    ("This is a fatal error log, program will exit.")  // The program will exit after output    ("This will not be executed because of Fatal above.")
}

3. Customize the log output location

logThe package outputs the logs to the standard error stream by default (), but can be passedMethod customize output location. Logs can be output to files, networks, or other compliantThe target of the interface.

Example: Output logs to file

package main
import (
    "log"
    "os"
)
func main() {
    file, err := ("")
    if err != nil {
        ("Failed to create log file:", err)
    }
    defer ()
    (file)  // Set log output to file    ("This log will be written to  file.")
}

4. Customize log prefixes and tags

logPackages allow custom log prefixes and formats to help identify the source or type of log. useMethods can set the prefix of the log, usingYou can control the marking of the log.

Log tags

logThe package provides the following tags (usingSetFlagsset up):

  • : Date (yyyy/mm/dd).
  • : Time (hh:mm).
  • : Microsecond time.
  • : Complete file path and line number.
  • : Short file name and line number.
  • : UTC time.
  • : The default mark, equivalent to |

Example: Custom log prefixes and tags

package main
import "log"
func main() {
    ("INFO: ")                  // Set log prefix    ( |  | )  // Set log mark    ("This is a customized log message.")
}

5. Create a custom logger

useYou can create a custom logger (Logger) and specify different output targets, prefixes, and tags. Multiple loggers can record different types of log information.

Example: Create two different loggers

package main
import (
    "log"
    "os"
)
func main() {
    // Create an error logger and output to standard error    errorLogger := (, "ERROR: ", ||)
    // Create an information logger and output it to a file    infoFile, err := ("")
    if err != nil {
        (err)
    }
    defer ()
    infoLogger := (infoFile, "INFO: ", |)
    ("This is an informational message.")
    ("This is an error message.")
}

The difference between log package and fmt package

Different uses

  • fmtThe package is mainly used to format input and output, suitable for outputting general information, and does not have log management functions.
  • logThe package is specially designed for logging and provides logging functions, suitable for the output of important information, errors, debugging information, etc. in the program.

Different output content

  • fmtPackage output has no timestamps and does not contain additional information by default.
  • logPackage output contains timestamps and can be set with additional tags and prefixes.

Output location

  • fmtThe output target of the package defaults to standard output (), can be passedDirects the output to the specified destination.
  • logThe default output of the package is standard error () and can be passedEasily modify the output target.

Log Level

  • fmtPackages do not have the concept of log level.
  • logThe package provides log-level support (e.g.FatalandPanic)。

Program Control

  • fmtPackage functions will not affect the program's control flow.
  • The program will be terminated.It will cause panic and help handle exceptions.

Summarize

  • fmtPackages are suitable for general formatted outputs, such as printing ordinary messages, debug outputs, etc.
  • logPackages are suitable for formal logging, providing features such as timestamps, log levels, log marks and custom outputs, which can better record and track the running status of the program.

This is the end of this article about the detailed explanation of the log package in go language. For more related go language log package content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!