Go - Change What Is Being Logged by the Standard Logger

发布时间 2023-09-29 15:04:17作者: ZhangZhihuiAAA

Problem: You want to change what the standard logger logs.


Solution: Use the SetFlags function to set flags and add fields to each log line.

 

The default behavior of the standard logger adds the date and time fields to each line of the log. 

The log package allows you to add information along with the default date and time fields. You can add these fields using the SetFlag function. The fields that are provided include:

Date
• The date in local time zone
Time
• The time in local time zone
Microseconds
• The microsecond resolution of the time field
UTC
• Use UTC time zone instead of local time zone if date or time fields are set
Long file
• The full filename and line number
Short file
• The filename and the line number
Message prefix position
• Move the prefix (from SetPrefix ) from the beginning of the line to before the start of the message


Here are some examples. You start by setting only the date field in the log:

log . SetFlags ( log . Ldate )
log . Println ( "Some event happened" )

This produces:

2022/01/24 Some event happened


If you want to add the time with microsecond details, you do this:

log . SetFlags ( log . Ldate | log . Lmicroseconds )
log . Println ( "Some event happened" )

Using the or operator on the flags, you set up the various fields to use with the log. Here’s the result from before:

2022/01/24 20:43:54.595365 Some event happened

 

The file fields are interesting because you can use them to tell you where the problems lie in the code through the logs:

log . SetFlags ( log . Ldate | log . Lshortfile )
log . Println ( "Some event happened" )

It gives you additional information about the filename and the line where the

problem occurred:
2022/01/24 20:51:02 logging.go:20: Some event happened