In Go, you can implement custom log formatters for log messages by creating a new type that implements the log.Formatter
interface. The log.Formatter
interface defines a single method called Format
, which takes a log entry and returns a formatted string.
Here's an example of how you can implement a custom log formatter:
package main
import (
"fmt"
"log"
"os"
)
type CustomFormatter struct{}
func (f *CustomFormatter) Format(entry *log.Entry) ([]byte, error) {
return []byte(fmt.Sprintf("[%s] %s\n", entry.Level, entry.Message)), nil
}
func main() {
logger := log.New(os.Stdout, "", 0)
logger.SetFormatter(&CustomFormatter{})
logger.Println("Hello, world!")
}
In this example, we define a CustomFormatter
struct that implements the Format
method of the log.Formatter
interface. The Format
method takes a log entry, which contains the log level and log message, and returns a formatted string.
In the main
function, we create a new log.Logger
instance and set its formatter to an instance of our CustomFormatter
struct. Then, we can use the logger to log messages as usual.
The CustomFormatter
in this example simply formats the log entry as "[log-level] log-message"
. You can customize the output format as per your needs by modifying the Format
method.