C # EventLog class
The EventLog class provides the function of C # interacting with Windows event logs. Many times we can write logs to Windows event logs.
Description: EventLog allows you to access or customize Windows event logs. The EventLog class provided by C # allows you to read existing logs, write items to logs, create or delete event sources, delete logs, and respond to log items. You can also create a log when creating an event source.
How to enable Windows Event Log
Right-click my computer and choose manage> event log.
Createeventsource
Overloaded. Create an application that can write event information to a specific log of the system.
Delete
Overloaded. Remove log resources.
Deleteeventsource
Overloaded. Remove the event source registration of the application from the event log.
Sourceexist
Overloaded. Search for the specified event source in the registry of the computer.
Writeentry
Overloaded. Write items to Event Logs.
Writeevent
Overloaded. Write localized event items to Event Logs.
To use Eventlog, we need to introduce the usingsystem. Diagnostics command space. The following two methods can be called when you catch exceptions or other methods.
Private void writeerror (string stext)
{
If (! EventLog. sourceexists (seventsource ))
EventLog. createeventsource (seventsource, seventlog );
EventLog. writeentry (seventsource, stext, eventlogentrytype. Error );
}
Private void writeinfo (string stext)
{
If (! EventLog. sourceexists (seventsource ))
EventLog. createeventsource (seventsource, seventlog );
EventLog. writeentry (seventsource, stext, eventlogentrytype. information );
}
The following is a simple example.
Try
{
'If (1/0 );
}
Catch (writable etion ex)
{
Writeerror (ex. Message );
}
In this way, we can successfully write data to Windows events ..:)
How to read and write EventLog
Reading and Writing EventLog (Event Log) in C # is quite simple, and the amount of code is relatively small.
1. Add system. diagnosticsname space;
Using system. diagnostics;
2. Declare An EventLog class instance.
EventLog Eventlog;
EventLog = new EventLog ("testevent", ".", "mysource ");
"Testevent" is to create a new EventLog name,
".": Indicates the Local Machine
"Mysource": Source Name
If no parameter is set, the default value is "application"
After setting it, you can read and write it.
Write:
EventLog. Source = "mysource ";
EventLog. writeentry ("log text ");
MessageBox. Show ("write complete! ")
Read:
Lstevent. Items. Clear ();
EventLog. log = "testevent ";
Foreach (eventlogentry in EventLog. Entries)
{
Lstevent. Items. Add (eventlogentry. Message );
}