How to use log levels to filter and route log messages to different destinations in Go?

In Go, log levels are often used to categorize log messages based on their severity. They can be used to filter and route log messages to different destinations such as the console, a file, or even a remote server. Here's how you can do it:

  1. First, import the log package:
import "log"
  1. Create a logger instance with the desired configuration:
logger := log.New(destination, prefix, flags)
  • destination: This could be the console (os.Stdout), a file (os.Create("log.txt")), or any other io.Writer implementation.
  • prefix: This is an optional prefix string that will be added to every log message.
  • flags: These are optional flags that control the log format, such as log timestamps (log.Ldate | log.Ltime) or log levels (log.LstdFlags | log.Lshortfile).
  1. Define different log levels and their numeric representations:
const ( LogLevelError = iota LogLevelWarning LogLevelInfo LogLevelDebug )
  1. Define a helper function to filter and log messages based on their log level:
func logWithLevel(level, logLevel int, message string) { if level <= logLevel { logger.Println(message) } }
  1. Use the logWithLevel function to log messages with the appropriate log level:
func main() { logLevel := LogLevelWarning // Set the desired log level logWithLevel(LogLevelInfo, logLevel, "This is an informational message.") logWithLevel(LogLevelWarning, logLevel, "This is a warning message.") logWithLevel(LogLevelError, logLevel, "This is an error message.") logWithLevel(LogLevelDebug, logLevel, "This is a debug message.") }

In the example above, logWithLevel filters the log messages based on the configured logLevel before forwarding them to the logger. By setting the appropriate log level, you can control which log messages are displayed or stored based on their severity.

Note: This implementation is a basic example and can be customized based on your specific needs. You can add more log levels, customize the message format, or even use a logging library like logrus or zap for more advanced features.