It is normal for an exception to occur in the program we wrote, but if an exception is not handled, It is abnormal. The Code of many programs is as follows:
Try
{
// A large part of code
}
Catch
{
// This field is null.
}
I can say responsibly that this approach is very irresponsible!
Although users cannot see any errors during browsing, they do not know what happened, the correct handling method should be to report the exceptions to the user in a friendly way. However, there is still a problem in doing so. Although exceptions can be reported to users in a friendly way, developers do not know what happened because of exceptions. It is even unclear when exceptions may occur.
In fact, one way to solve the above problems is to record the exceptions when they occur. There are n record methods, for example:
1. Record exceptions to the database.
2. Record exceptions to text files.
3. Record exceptionsXMLFile.
4. Send the exception to the developer's mailbox by email.
5. Send the exception to the developer's mobile phone via text message.
6 ,......
Here, we will introduce a cool method: Writing exceptions to system logs. That is to say, we can view the exceptions in the event viewer.
For convenience, create an appexception. CS file in the app_code folder of the website and perform the following steps:
1. Add "using system. diagnostics;" reference. The diagnostics namespace provides classes that can interact with system processes, event logs, and performance counters.
2. Create a method named predictionlog () to write a log in the event log of the application.
3. In the exceptionlog () method, an EventLog class is first instantiated, which can interact with Windows event logs.
4. In the EventLog class, two attributes are important: one is the source attribute, which is used to set the log generation source, and the other is the log details. We can pass the parameter to the predictionlog () method. See the following code.
/// <Summary>
/// Write logs to the "application" Event Log
/// </Summary>
/// <Param name = "logsource"> log source </param>
/// <Param name = "logcontents"> log details (log description) </param>
Public void exceptionlog (string logsource, string logcontents)
{
// Create an EventLog instance
EventLog log = new EventLog ();
// Set the EventLog Source
Log. Source = logsource;
// Write EventLog to the event log of "application"
Log. writeentry (logcontents );
}