C #. NET log information written to Windows Log Solution

Source: Internet
Author: User
Tags net command

1. Purpose
The development and maintenance of application systems are inseparable from the log system. Choosing a powerful log system solution is an important part of the application system development process. There are many log system solutions in the. net environment, among which log4net is the best.
In Windows and later, there is a Windows Log System, which includes Application Event Logs, System logs, and Security logs, event Logs can also be custom logs. The. net Framework also provides corresponding classes and interfaces to use Application Event Logs or Custom Event Logs. Using Windows logs can better combine the application system and the operating system. Compared with using a custom log system, it is easier to query and manage logs because of the support of the operating system. In practical applications, you can select an appropriate log solution based on the actual situation, or you can customize the log system and Windows Log System to use both log solutions at the same time.
2. How to Use Windows logs
2.1 Method Overview
An EventLog class is provided in. net Framework. You can use the EventLog class to add new event log entries or obtain existing entries from server Event Logs. The EventLog class includes a WriteEntry () method that can be used to write a new event to the event log. When writing a new entry to the event log, the specific event source is used to write the entry into the specific event log.
The event source is unique for event logs. In Windows and later operating systems, there is an event log: Application Event Logs, System logs, and Security logs, the system allows you to customize Event Logs. You can use the EventLog class to add log entries to Application Event Logs or Custom Event Logs. The event source is equivalent to the next level directory of the event log. Each log entry must correspond to an event source. The EventLog class can create a custom event log or an event source, which can be created in the Application Event Log, you can also create it in Custom Event Logs. Shows the Windows Log System:
To facilitate log differentiation and viewing between different application systems, the event source is generally created in Custom Event Logs, and multiple Event Logs can be created, one event log can also create multiple event sources.
2.2 Event Logs and event Source Creation Methods
When creating a new event log or event source, you actually add an entry to the Registry. Because writing the registry requires special permissions, permission and security issues exist 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 use of Windows logs in Web projects. The use of Application projects is similar to that of Web projects. You just need to discard the permissions and Security Processing in Web projects.
In a Web project, when you use asp.net to create an event log or an event source for the System, the following error message may be returned: System. security. securityException: the requested registry access is not allowed. This is because the default account for running the asp.net process is ASPNET (NetworkService under IIS6.0), and this account has only the read permission by default and has no write permission, so it cannot create Event Logs or event sources. There are three solutions to this problem:
A. Before running the program, 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:
1. Click 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 column sub-key in the Registry Editor:
HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Services \ Eventlog
④ Right-click "Eventlog", click "new", and click "item". A new project will be created at the next level of "Eventlog" and named "TDDN ", the TDDN item is the event log, which can be named according to the actual situation. For example, it can be named as the project name.
⑤ Right-click the "TDDN" item, click "new", and click "item". A new item will be created at the next level of "TDDN" and named "Weblog ", the Weblog item is the event source, which can also be named based on the actual situation.
6. Close the Registry Editor.
In this way, the event log and event source are created. If you need multiple event logs or event sources, repeat the above process. This method requires you to be familiar with the Registry, and the operation may be a little complicated. You can write a class to configure the Registry. You only need to run this class to add the corresponding project, eliminating the hassle of manual addition, this is the second solution. The method is as follows:
B. There is an EventLogInstaller class in the System. Diagnostics namespace. It can create and configure the Event Logs and event sources to be read and written by the application at runtime. Follow these steps to create an event log and event source using the EventLogInstaller class:
① Use C # to create a "class library" named EventLogSourceInstaller ".
② Add a reference to System. Configuration. Install. dll in this project.
③ Rename automatically generated Class1.cs to MyEventLogInstaller. cs.
④ Write the following code in MyEventLogInstaller. cs:
Using System;
Using System. Diagnostics;
Using System. ComponentModel;
Using System. Configuration. Install;
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.
MyEventLogInstaller. Source = "WebLog ";
// Set the Log that source is created in
MyEventLogInstaller. Log = "TDDN ";
Installers. Add (myEventLogInstaller );
}
}
}
⑤ Generate this project and get EventLogSourceInstaller. dll.
⑥ Open the Visual Studio. NET command prompt and go to the directory where EventLogSourceInstaller. dll is located.
7. Run this command to create the event log and event source. Run the command InstallUtil EventLogSourceInstaller. dll.
In this way, the program creates an event log: TDDN in the system, and creates an event Source: WebLog under the event log TDDN.
The above two solutions are to manually add Event Logs and event sources to the system before the application system runs. In this way, there is no security permission problem and there is no security risk. A more convenient method allows 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, alternatively, you can give the asp.net process a simulated account with greater permissions. The implementation of simulated accounts is complicated, and the functions and security are no different from those of upgrading the ASPNET account. The method used here is to improve the permissions of the ASPNET account. The third solution is as follows:
C. To improve the permissions of an ASPNET account, you can directly add read and write permissions to the system to the ASPNET account in Windows system management. However, this poses a serious security problem, the asp.net process has the permission to directly read and write the operating system, which brings great security risks to the system. The method used to improve the ASPNET account permissions here is to grant the operation permissions of system logs to the ASPNET account. Although there are still some security risks, the risks have been greatly reduced, in addition, Event Logs and event sources can be freely created within the program, greatly improving flexibility. The methods for improving the permissions of an ASPNET account are as follows:
① Click Start, Run, and enter regedit to open the Registry Editor.
② Locate the column sub-key in the Registry Editor:
HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Services \ Eventlog
③ Right-click the Eventlog project, select the "access permit" option in the pop-up menu, find the locally added ASPNET account, and grant the read and write permissions.
In this way, the ASPNET account has the permission to read and write system logs, and you can freely create Event Logs and event sources in the program as needed. You can create an event log and an event source in a program as follows:
Call the CreateEventSource method of the EventLog class and specify the data source string and the name of the event log to be created. If the event log name is null (""), the default Event Log name is Application, in this way, no new event logs will be created, but the specified data source will be created for the Application Event Logs. If a new event log is created, only the first eight letters of the specified string are counted when determining whether the event log name is unique. The following code is used:
System. Diagnostics. EventLog. CreateEventSource ("WebLog", "TDDN ");
Create an event log as TDDN, and create an event source WebLog under this event log. To create a custom event log on a remote computer, specify the computer name as the third parameter. The following code provides an example:
System. Diagnostics. EventLog. CreateEventSource ("WebLog", "TDDN", "myserver ");
This event log and event source will be created on the remote computer myserver.
2.3. How to Write Windows logs
The problem of Event Logs and event Source Creation is solved, and then the log information can be written to Windows system logs in the program. The write method is to first create an instance of the EventLog class, associate its Source attribute with the event Source name, and finally call the WriteEntry method to add log information to the event log. The following is a simple sample code for writing system logs:
EventLog eventLog = null;
If (! (EventLog. SourceExists ("WebLog "))){
EventLog. CreateEventSource ("WebLog", "TDDN ");
}
If (eventLog = null ){
EventLog = new EventLog ("TDDN ");
EventLog. Source = "WebLog ";
}
EventLog. WriteEntry ("This is error! ", EventLogEntryType. Error );
}
In the above section, first determine whether the data Source "WebLog" exists. If the CreateEventSource method is not called to create the event Source, then associate the event Source with the Source attribute of the EventLog class for write operations. The first parameter passed to the WriteEntry method represents the log message to be logged and can be written to any message. The second parameter represents the event log type.
A. Event Log Type Classification
The Event Log type is used to indicate the severity of the event log. Each event must have a single type, which is indicated by the application when reporting the event. Event Viewer uses this type to determine which icon is displayed in the log List View. It is divided into the following five categories:
① Error: An Error event that indicates a serious problem that the user should know (usually a loss of functionality or data ).
② FailureAudit: a failure Audit event that indicates a security event that occurs when an audit access attempt fails (for example, an attempt to open a file fails.
③ Information: an Information event that indicates important and successful operations.
④ SuccessAudit: a successful Audit event that indicates a security event that occurs when the audit access attempt is successful (for example, a successful logon.
⑤ Warning: a Warning event that indicates a problem that is not immediately important, but this issue may indicate conditions that will cause problems in the future.
In practical applications, selecting an appropriate Event Log Type can make log records clearer and clearer, helping developers and maintenance personnel better monitor and maintain the application system.
B. For five types of Event Logs, you can write a common class in the application and write a method for each type to write Event Logs.
The following is a code snippet of a custom generic class:
Public void Error (string sourceName, string message ){
EventLog eventLog = null;
If (! (EventLog. SourceExists (sourceName ))){
EventLog. CreateEventSource (sourceName, "TDDN ");
}
If (eventLog = null ){
EventLog = new EventLog ("TDDN ");
EventLog. Source = sourceName;
}
EventLog. WriteEntry (message, EventLogEntryType. Error );
}
Public void Warning (string sourceName, string message ){
EventLog eventLog = null;
If (! (EventLog. SourceExists (sourceName ))){
EventLog. CreateEventSource (sourceName, "TDDN ");
}
If (eventLog = null ){
EventLog = new EventLog ("TDDN ");
EventLog. Source = sourceName;
}
EventLog. WriteEntry (message, System. Diagnostics. EventLogEntryType. Warning );
}
Similarly, you can write three other types of Event Logs. This method transmits the event source (sourceName) and log message as parameters, which improves the flexibility of Event Log writing.
C. Call the common event log Writing Method
The call of common methods is very simple. The following code snippet is an example of calling the Error method in a common class:
String strSourceName = "WebLog ";
CoustomEventLog log = new CoustomEventLog ();
Log. Error (strSourceName, "This is Error! ");
StrSourceName is the event source, and log is an instance of the CoustomEventLog class (that is, a common class). Then, call the Error method to send the log message "This is Error !" It is written to the event log.
You can also write the exception information thrown in the program into the event log:
String strSourceName = "WebLog ";
CoustomEventLog log = new CoustomEventLog ();
Try {
// Execute the event

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.