Manage Log in Golang
Introduction
Logging is crucial in software development, as it aids in debugging, monitoring, and analyzing software applications. There are several Go packages available for logging:
- log
- logrus
- zap
- zerolog
- glog
log
This package is part of the standard Go Library and provides basic logging capabilities, making it suitable for logging in smaller applications.
Basic Logging
log.Print("Hello, log!")
log.Println("Hello with newline")
log.Printf("Hello, %s!", "formatted")
Output:
2024/04/28 11:28:37 Hello, log!
2024/04/28 11:28:37 Hello with newline
2024/04/28 11:28:37 Hello, formatted!
Log Prefix and Flags
The log package enables the addition of a prefix to each log entry, and allows for format control through the use of flags.
log.SetPrefix("prefix: ")
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
log.Println("This is a log with prefix-1")
log.Println("This is a log with prefix-2")
Output:
prefix: 2024/04/28 11:33:17 main.go:33: This is a log with prefix-1
prefix: 2024/04/28 11:33:17 main.go:34: This is a log with prefix-2
Levels of Severity
While the log package doesn’t directly support log levels, you can simulate them by using different prefixes or defining custom logging functions.
func info(args ...interface{}) {
log.SetPrefix("INFO: ")
log.Print(args...)
}
func error(args ...interface{}) {
log.SetPrefix("ERROR: ")
log.Print(args...)
}
Logging Fatal and Panic Errors
The log.Fatal*
functions will log the message and then call os.Exit(1)
.
The log.Panic*
functions will log the message and then cause a panic.
log.Fatal("This is a fatal error")
log.Panic("This is a panic")
logrus
logrus
is an enhanced logging package that extends the functionality of the log
package. It’s especially suited for more complex applications. Here are some benefits of logrus
:
- Structured Logging: Logrus supports logging in a structured format, such as JSON.
- Log Levels: Logrus offers multiple logging levels (debug, info, warn, error, fatal, and panic), which allows for message output based on severity.
- Hooks: Logrus enables the addition of hooks to send logs to external systems or trigger actions when certain log messages occur.
Basic Logging
logrus.Info("This is an info message")
logrus.Warn("This is a warning message")
logrus.Error("This is an error message")
Output:
INFO[0000] This is an info message
WARN[0000] This is a warning message
ERRO[0000] This is an error message
Structured Logging
Employ structured logging to incorporate additional fields into the log entries.
logrus.WithFields(logrus.Fields{
"username": "Sumudu Liyanage",
"id": 123,
}).Info("User logged in")
Output:
INFO[0000] User logged in id=123 username="Sumudu Liyanage"
Customizing Output
Logrus provides the capability to customize the output format. For example, you can choose to log in JSON format.
logrus.SetFormatter(&logrus.JSONFormatter{})
logrus.WithFields(logrus.Fields{
"username": "Sumudu Liyanage",
"id": 123,
}).Info("User logged in")
Output:
{"id":123,"level":"info","msg":"User logged in","time":"2024-04-28T11:56:35+05:30","username":"Sumudu Liyanage"}
Hooks
Hooks allow for integration with other systems. For instance, you can add a hook to transmit error-level logs to a monitoring service.
zap
zap
is a high-performance logging library designed for applications needing quick, structured logging with minimal overhead. If speed is a priority, zap
is a preferable choice over logrus
.
logger, err := zap.NewProduction()
if err != nil {
panic(err)
}
logger.Info("This is an info message", zap.String("key", "value"), zap.Int("number", 1))
Output:
{"level":"info","ts":1714287036.2461052,"caller":"hello-world/main.go:14","msg":"This is an info message","key":"value","number":1}
zerolog
zerolog is a high-performance logging library for Go, specifically designed for zero-allocation JSON logging. It minimizes memory allocations by directly writing JSON log events to the output, such as io.Writer
, thus avoiding the overhead of temporary objects.
// Set global log level
zerolog.SetGlobalLevel(zerolog.InfoLevel)
// Configure zerolog to write to stdout with human-friendly formatting
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout})
// Logging with context
log.Info().Str("role", "myrole").Msg("This is an info message")
log.Debug().Int("id", 123).Msg("This is a debug message that won't be displayed")
log.Error().Msg("This is an error message")
Output:
12:38PM INF This is an info message role=myrole
12:38PM ERR This is an error message
glog
glog
provides a comprehensive set of features for managing verbosity-based logging, beneficial for precise control over the granularity of log output.
Instead of traditional log levels (info, warn, error), glog
utilizes verbosity levels represented by integers. Higher numbers correspond to more detailed logs, giving developers the flexibility to determine the extent of logging required.
// Basic logging
glog.Info("This is an informational message")
glog.Warning("This is a warning message")
glog.Error("This is an error message")
// Conditional logging based on verbosity level
if glog.V(2) {
glog.Info("This is a verbose level 2 message")
}
Reference: https://dev.to/sumuduliyanage/insights-into-go-logging-2egh