Logging
This program demonstrates the use of the standard log
package and the log/slog
package (structured logger) in Go. Let me break down the code and provide some explanations:
Output
Explanation:
Standard Logger (
log
package):The program starts by using the standard logger (
log.Println
) with various log messages.Flags for the standard logger are modified to include microseconds and file/line information.
Custom Logger (
log.New
):A custom logger (
mylog
) is created usinglog.New
with a specific output (os.Stdout
), prefix ("my:"), and flags.The prefix is later modified to "ohmy:".
Buffered Logger (
log.New
withbytes.Buffer
):Another logger (
buflog
) is created that writes log messages to a buffer (bytes.Buffer
).The content of the buffer is printed to the standard output.
Structured Logger (
log/slog
package):The
slog
package is used to create a structured logger (myslog
) with a JSON formatter.Log messages are provided with additional key-value pairs.
You can run the program to observe the different log messages and how they are formatted based on the logger configurations:
Last updated
Was this helpful?