“This is the 13th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

Recently, there is a need to write a small application on the Windows platform, and also need to record a point of log, but the amount is not very large, so I began to study whether the log can be recorded to the Windows own log system, and then through the event manager to view and manage the log.

implementation

A package called EventLog is available in the golang official non-standard library golang.org/x/sys/windows library, which defines methods related to operating Windows logs.

It is available after installation using Go Get

go get golang.org/x/sys
Copy the code

The method of using EventLog is not complicated.

Create a Log instance using eventlog.open. This method requires you to pass in a string indicating where the logs came from, usually the program name.

Once we get the Log instance, we can call the Info, Error, and Warning methods to write logs to the event manager. Unlike other log libraries, you need to specify an event ID (a 32-bit unsigned integer) when writing logs to the Windows OS event manager.

Call the Close method to Close the log instance after writing the log.

What’s the use of an event ID?

A more intuitive role is used for monitoring and statistics, for example, as long as you know what the event ID of the security-related log is, you can help determine whether there is a security risk on the current computer.

You can see the security-related event codes defined by Windows here -> Windows Security Log Events.

The test case code looks like this:

func Test_log(t *testing.T) {
	log, err := eventlog.Open("Kovogo")
	iferr ! =nil {
		panic(err)
	}
	log.Error(100."This is an error log.")
	log.Close()
}
Copy the code

After running the test case, we can find the log we wrote in the Windows Log/application directory in the event Manager.

To open the event manager, type eventvr.msc on the command line, and you can view the error log we just wrote in the event manager.

Matters needing attention

  • The default log mechanism of Windows overwrites previous logs when the log file size exceeds the upper limit. The default log file size is 20MB

Right click on the corresponding project and click on “Properties” to see the image below, with options to adjust the behavior of Windows logs

  • Clearing Windows logs is convenient, but it also generates a record of the log being cleared

As shown in the figure below: After the application log is cleared, an application log was cleared record is generated under the system log

conclusion

After the investigation, I decided to use Windows log as a bypass log system to help judge whether the main log is written into the log program by myself.