SoFunction
Updated on 2025-03-06

Solution to write log information to Windows logs in c#.NET

1. Purpose
The development and maintenance of application systems are inseparable from the log system. Choosing a powerful log system solution is a very important part of the application system development process. There are many types of log system solutions in the .net environment, and log4net is the leader among them.
In Windows 2000 and above operating systems, there is a Windows log system, which includes application event logs, system logs and security logs. The event logs can also be custom logs. The corresponding classes and interfaces are also provided in the .net Framework to use application event logs or custom event logs. Using Windows logs can better combine the application system with the operating system. Compared with simply using a custom log system, it is more convenient to query and manage logs with the support of the operating system. In actual applications, according to actual conditions, you can choose a suitable logging solution, or you can customize the logging system and Windows logging system to use both at the same time.
2. Methods to use Windows logs
2.1. Method Overview
A class EventLog is provided in the .net Framework. Use the EventLog class to add new event log entries or get existing entries from the server event log. The EventLog class includes a WriteEntry() method, which can be used to write a new event to the event log. When writing a new entry to the event log, a specific event source is used to write the entry to the specific event log.
The event source is unique to the event log. In Windows 2000 and above operating systems, there is an event log: application event log, system log and security log, and the system allows custom event logs. Using the EventLog class, you can add log entries to the application event log or to a custom event log. The event source is equivalent to the next level directory of the event log, and each log entry must correspond to an event source. The EventLog class can create a custom event log or an event source. The event source can be created in the application event log or in the custom event log. The Windows log system is shown in the figure below:
In order to facilitate log distinction and viewing between different application systems, event sources are generally created in custom event logs, multiple event logs can be created, and multiple event sources can be created in one event log.
2.2. Methods for creating event logs and event source
When creating a new event log or event source, you are actually adding an entry to the registry. Since writing a registry requires special permissions, there are permissions and security issues when creating event logs and event sources in a web project. This problem does not exist in the Application project. This article focuses on the usage methods of Windows logs in a web project. The usage methods in the Application project are similar to those in a web project. Just abandon the permissions and security processing in the web project. This article will not repeat them again.
In a web project, when creating an event log or an event source to the system, you may get the following exception error message: : The requested registry access is not allowed. This is because the default account for running the process is ASPNET (NetworkService under IIS6.0), and this account only has read permissions by default and does not have write permissions, so event logs or event sources cannot be created. The solutions to this problem include improving the permissions of the ASPNET account, not creating event logs or event sources within the program, etc. There are mainly three solutions:
A. Before the program runs, define the event log and event source to be used, open the registry editor, and manually add the event log and event source to the registry. The main steps are as follows:
①    Click on the "Start" menu, and then click "Run".
②       Enter "regedit" in the "Open" box of "Run", and then press the OK button to open the Registry Editor.
③      Find the following subkeys in the registry editor:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog
④    Right-click "Eventlog", click "New", and then click "Item", and a new project will be created at the next level of "Eventlog", and the project will be named "TDDN". The TDDN item is the event log. This item can be named according to the actual situation, such as it can be named as the project name.
⑤    Right-click on the "TDDN" item, click "New", and then click "Item", and a new item will be created at the next level of "TDDN", name this item "Weblog", the Weblog item is the event source, and this item can also be named according to the actual situation.
⑥    Close the Registry Editor.
In this way, the event log and event source are built. If multiple event logs or event sources are needed, repeat the above process. This method requires more familiarity with the registry and may be a bit complicated to operate. You can write a class to configure the registry. As long as you run the class, you can add the corresponding project, eliminating the cumbersomeness of manual addition. This is the second solution, the method is as follows:
B. There is an EventLogInstaller class in the namespace, which can create and configure the event logs and event sources to be read and written by the application at runtime. You can use the EventLogInstaller class to create an event log and event source through the following steps:
①   Use C# to create a "class library" called EventLogSourceInstaller.
②     Add a reference to this project.
③     Rename the automatically generated.
④     Write the following code in:
using System;
using ;
using ;
using ;
namespace EventLogSourceInstaller {
[RunInstaller(true)]
public class MyEventLogInstaller: Installer{
public  EventLogInstaller myEventLogInstaller;
public MyEventLogInstaller(){
//Create Instance of EventLogInstaller
myEventLogInstaller = new EventLogInstaller();
// Set the Source of Event Log, to be created.
 = "WebLog";
// Set the Log that source is created in
 = "TDDN";
(myEventLogInstaller);
}
}
}
⑤     Generate this project and get it.
⑥    Open the Visual Studio .NET command prompt and go to the directory you are in.
⑦     Run this command to create event logs and event sources. The run method is: enter the command InstallUtil .
In this way, the program creates an event log: TDDN in the system, and creates an event source: WebLog under the event log TDDN.
Both of the above solutions are manually added to the system before the application system is run. There is no security permission problem and there is no security risk. A more convenient method can also allow the program to automatically create event logs and event sources when the application system is running. This method must improve the system operation permissions of the ASPNET account, or give the process a simulated account with greater permissions. The implementation of a simulated account is relatively complex, and there is no difference between function and security and improvement of ASPNET account. The method adopted here is to increase the permissions of ASPNET account. Here is the third solution:
C. Improve the permissions of ASPNET account, you can directly add read and write permissions to the system to the ASPNET account in Windows system management. However, this has serious security problems. The process has permission to read and write the operating system directly, which will bring great security risks to the system. The method to improve the permissions of ASPNET account adopted here is to only assign the operation permissions of the system log to the ASPNET account. Although there are certain security risks, the hidden dangers have been greatly reduced, and event logs and event sources can be created freely within the program, greatly improving flexibility. The methods for increasing permissions of ASPNET account are as follows:
①    Click "Start", "Run", enter "regedit" to open the registry editor.
②       Find the following subkeys in the registry editor:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog
③      Right-click on the Eventlog project, select the "Access License" option in the pop-up menu, and then find the ASPNET account of the machine to add it and give it read and write permissions.
In this way, the ASPNET account has the permission to read and write system logs, and can freely create event logs and event sources in the program according to the situation. The method of creating event logs and event sources in a program is as follows:
Call the CreateEventSource method of the EventLog class and specify the data source string and the event log name to be created. If the event log name is specified as empty (""), the event log name will default to Application. This will not create a new event log, but a specified data source will be created for the application event log. If a new event log is created, only the first 8 letters of the specified string will be calculated when determining whether the event log name is unique. The following code looks like:
("WebLog", "TDDN");
An event log is created as TDDN, and an event source WebLog is created under the event log. To create a custom event log on a remote computer, specify this computer name as the third parameter. The following code provides an example:
(" WebLog ", " TDDN ", "myserver");
The event log and event source will be created on the remote computer myserver.
2.3. Methods to write to Windows logs
The problem of event log and event source creation has been solved. Next, you can write log information into the Windows system log in the program. The write method is to first create an instance of the EventLog class, associate its Source property with the event source name, and finally call the WriteEntry method to add log information to the event log. Here is a simple example code to write to the system log:
EventLog eventLog = null;
if (!(("WebLog"))){            
("WebLog", "TDDN");
}
if (eventLog == null){
eventLog = new EventLog("TDDN");
 = "WebLog";

("This is error!", );
}
In the above program segment, first determine whether the data source "WebLog" exists. If there is no existence, call the CreateEventSource method to create the event source, and then associate the event source with the Source property of the EventLog class to perform the write operation. The first parameter passed to the WriteEntry method represents the log message to be recorded and can be written to any message. The second parameter represents the type of event log.
A. Event log type classification
The type of event log is used to indicate the severity of the event log. Each event must have a single type, which the application will indicate when reporting an event. The event viewer uses this type to determine which icon is displayed in the list view of the log. It is divided into the following five categories:
①    Error: Error event, which indicates a serious problem that the user should be aware of (usually the loss of functionality or data).
②      FailureAudit: Failure audit event, which indicates a security event that occurs when an audit access attempt fails (such as a failed attempt to open a file).
③     Information: Information event, which indicates an important and successful operation.
④      SuccessAudit: Success audit event, which indicates a security event that occurs when the audit access attempt is successful (such as successful login).
⑤    Warning: Warn events, which indicate issues that are not immediately of importance, but this issue may indicate conditions that will cause problems in the future.
In actual applications, choosing the appropriate event log type can make logging clearer and clearer, helping developers and maintainers better monitor and maintain application systems.
B. For the five types of event logs, you can write a common class in the application and write a method for each type to write an event log.
Here is a code snippet for a custom general class:
public void Error(string sourceName, string message){
EventLog eventLog = null;
if (!((sourceName))){
(sourceName, "TDDN");
}
if (eventLog == null){
eventLog = new EventLog("TDDN");
 = sourceName;
}
(message, );
}
public void Warning(string sourceName, string message){
EventLog eventLog = null;
if (!((sourceName))){
(sourceName, "TDDN");
}
if (eventLog == null){
eventLog = new EventLog("TDDN");
 = sourceName;
}
(message,);
}
Similarly, you can write out other three types of event log writing methods. This class of methods passes the event source (sourceName) and log message as parameters, which can improve the flexibility of event log writing.
C. Calling method of writing general-class event logs
The call to a general class method is very simple. The following code snippet is an example of calling the Error method in a general class:
string strSourceName="WebLog";
CoustomEventLog log=new CoustomEventLog();
(strSourceName,"This is Error!");
strSourceName is the event source, log is an instance of the CoustomEventLog class (i.e., a general class), and then call the Error method to write the log message "This is Error!" to the event log.
You can also write exception information thrown in the program to the event log:
string strSourceName="WebLog";
CoustomEventLog log=new CoustomEventLog();
try{
//Execute event