Exception Handling and log tracing in asp.net and asp.net Exception Handling
For Exception Handling, everyone must understand try {} catch () {} finally {}. I will not talk about it here. Through "debugging"-"exception" in VS, the exception hierarchy in. NET is displayed in the Common Language Runtime Exceptions column in the pop-up exception dialog box.
Custom exception:
If the exception classes provided by the system cannot meet the needs of application system development, or the development team needs a set of custom exception handling mechanisms, you can create custom exception classes. The custom Exception class should inherit from the ApplicationException class directly and indirectly, and it is better to have a good name: Incorrect descriptive name + Exception. Three constructors should be defined: default constructor, constructor that accepts error messages and constructor of internal exception objects. All the exceptions thrown by CLR are inherited from SystemException. The exceptions thrown by the application must be inherited from ApplicationException. In this way, developers can write catch blocks to catch exceptions thrown by all CLR or exceptions thrown by all applications.
Recommended shineqiujuan by andreslly
Record exception:
Web applications may have thousands of users. In addition to displaying error information to users, exceptions may need to be recorded. For example, the web server is overloaded and some problems occur intermittently multiple times .. NET Framework provides a variety of logging tools, such as sending E-mail when an error occurs and adding it to database records or read/write files. A better way to handle windows events is to use windows events. windows event programs are a built-in tool for recording system or application logs in windows and can be used by any application.
Open the Event Viewer in the management tools on the Control Panel to view windows event logs. General event categories include applications (used to record errors or notifications of any application, and ASP can usually be recorded here.. NET application exception) system (used to record operating system-related events) Security (used to record security-related issues, used only by the operating system ). Click an event in these event categories to display the event Details window. Right-click these event categories to clear the logs, save the logs, create a new log view, open the file, and set the maximum size of the log file through attributes. If the log size exceeds the specified upper limit, expired event logs are automatically cleared.
Write exceptions to windows Event Logs
The EventLog class in the System. Diagnostics namespace can read and write Event Logs.
Protected void button#click (object sender, EventArgs e)
{
Try
{
Int a = 1; int B = 0;
Int c = a/B;
}
Catch (Exception ex)
{
Label1.Text = "<B> error Message: </B>" + ex. Message + "<br/>"; error description
Label1.Text + = "<B> Error Source: </B>" + ex. Source + "<br/>"; which assembly is returned with an error
Label1.Text + = "<B> stack tracing: </B>" + ex. StackTrace;
Label1.ForeColor = System. Drawing. Color. Red;
Determine if there is any event of this type in the windows event log. We can see in the event log that each event has an event ID, and events with the same event ID belong to the same type of event.
If (! EventLog. SourceExists ("division operation error "))
{
If this type of event does not exist, register this type of event and register this type of event in our custom event category. The second parameter is the application by default.
EventLog. CreateEventSource ("division operation error", "ASPNET Event Log ");
}
The EventLog constructor can open the specified event category (equivalent to a table)
EventLog elog = new EventLog ("ASPNET Event Log ");
Specifies the event source string, which will appear in the event category Source column (equivalent to the Source Field)
Elog. Source = "from web server ";
Write an event item to the specified event category. The event description, event type, and event ID can be specified (equivalent to a record)
Elog. WriteEntry (ex. Message, EventLogEntryType. Error );
}
}
It can be seen that windows event logs are like a database. Event categories are different tables, and the event items in the logs are records.
Program to view event logs (equivalent to viewing all records of a table in the database)
Complex, specifying the displayed Field
First, create an event item entity class.
Public class EventItem
{
Public string EventType {get; set;} Event Type
Public string EventMessage {get; set;} Event Description
Public DateTime EventTime {get; set;} event occurrence time
Public string EventSource {get; set;} event Source
Public EventItem (string eventtype, string eventmessage, DateTime eventtime, string eventsource)
{
EventType = eventtype;
EventMessage = eventmessage;
EventTime = eventtime;
EventSource = eventsource;
}
}
Create a list class to save all the event items in an event category.
Public class EventList: List <EventItem>
{
Public EventList (string logname)
{
If (! EventLog. Exists (logname) is used to determine whether the event category Exists (whether the table Exists)
{
Return;
}
Else
{
EventLog elog = new EventLog (logname); open an event category
Foreach (EventLogEntry item in elog. Entries) event items are of the EventLogEntry type. The Entries attribute can be used to obtain all event items in the event category.
{
EventItem eventitem = new EventItem (item. EntryType. ToString (), item. Message, item. TimeGenerated, item. Source );
This. Add (eventitem );
}
}
}
}
Protected void button#click (object sender, EventArgs e)
{
String logname = TextBox1.Text;
EventList eventlist = new EventList (logname );
GridView1.DataSource = eventlist;
}
Simple: The retrieved event item contains the default Field
Protected void button#click (object sender, EventArgs e)
{
String logname = TextBox1.Text;
EventLog elog = new EventLog (logname );
GridView1.DataSource = elog. Entries; The collection type returned by the Entries attribute is EntryCollection, which inherits IEnumerable and can be bound.
GridView1.DataBind ();
}
Use log4net to record logs
Http://blog.csdn.net/zhoufoxcn/archive/2010/11/23/6029021.aspx | recommended
Http://www.cnblogs.com/dragon/archive/2005/03/24/124254.aspx | recommended
Http://www.cnblogs.com/xugang/archive/2008/04/09/1145384.html
Http://blog.csdn.net/zhoufoxcn/archive/2008/03/26/2220533.aspx
Http://blog.csdn.net/antyi/archive/2007/04/30/1592812.aspx
The following configuration is used to generate a txt log file every day. Other methods are described in the first link, and the second link theory is very good.
<Log4net>
<Root>
<Appender-ref = "RollingLogFileAppender_DateFormat"/>
</Root>
<Appender name = "RollingLogFileAppender_DateFormat" type = "log4net. Appender. RollingFileAppender">
<File value = "Log/Dailylog.txt"/>
<AppendToFile value = "true"/>
<RollingStyle value = "Date"/>
<DatePattern value = "yyyyMMdd"/>
<Layout type = "log4net. Layout. PatternLayout">
<ConversionPattern value = "date [% date] thread ID [% thread] file name [% file] line number [% line] %-5 current priority level [% level] Error description [% message] "/>
</Layout>
</Appender>
</Log4net>
Page tracking
Although ASP. NET error pages provide very useful information, sometimes developers need more detailed information to correct errors in applications. For example, an application executes a property or tracks logical errors in the application. Sometimes the application may generate some invalid data, but there is no obvious exception triggering. ASP. NET provides the tracking function, allowing developers to report diagnostic information in a more convenient and flexible way.
In addition to setting <% @ Page Trace = "true" %> at the Page level, you can also set it in code, such:
Protected void Page_Load (object sender, EventArgs e)
{Page. Trace. IsEnabled = true ;}
The Trace attribute of the Page object is an instance of the System. Web. TraceContext class. The benefit of using code is that you can enable and disable page tracing based on a specific environment.
After this operation, ASP. NET tracing provides a large amount of diagnostic information:
1. Request details (SessionID, request type, request time, request status code, Request Encoding, response encoding)
2. Tracking Information (the processing process of the page before the tracing information display page is sent to the client, and the detailed execution duration of the page is provided)
3. Control tree (display all runat = server controls on the page)
4. Session Status and Application status (displays the keys, values, types, and Application states of all sessions in the current Application)
5. Request Cookie set (name, value, and size of Cookies requested by web browsers) response Cookie set (name, value, and size of Cookies sent by web servers)
6. header set (lists all HTTP header information (a small piece of information sent to the web server as part of the request, including request information, supported content types, and languages ))
7. Response Header set (lists part of the information sent to the client as a response)
8. Form set (form information submitted in post mode), but 8 or 9 is only the value of the server control in the form (ASP. NET page tracing only tracks server controls ?)
9. Querystring set (form information submitted in get mode/Name and value in query string)
10. Server variables (usually not required)
The above is only for the use of tracking a page, you can set in the root web. config, start the tracing of the entire application, configure in <system. web>:
<System. web>
<Trace enabled = "true" requestLimit = "10" pageOutput = "false" traceMode = "SortByTime" localOnly = "true"/>
</System. web>
RequestLimit (tracking information of the maximum number of HTTP requests) traceMode (in which order) localOnly (tracing information is only displayed locally)
To access these request information, you only need to access trace. axd in the root directory (which does not exist.
By the way, everyone is talking about the website of program life. I also recommend it.
How to handle aspnet exceptions
Public static ThemeWordDataSet getThemeClassMainThemeWord (string SQL)
{
String strCon = ConfigurationManager. receivettings ["ConnStr"];
SqlConnection conn = new SqlConnection (strCon );
SqlDataAdapter myDataAdapter = new SqlDataAdapter (SQL, strCon );
ThemeWordDataSet themeWordDataSet = new ThemeWordDataSet ();
Try
{
If (conn. State = ConnectionState. Closed)
{
Conn. Open ();
}
MyDataAdapter. Fill (themeWordDataSet, "ThemeClassMainThemeWord ");
Catch (Exception ex)
{
// Obtain the exception information
Info = ex. Message;
// You can also directly throw
// Throw (ex );
}
Finally
{
Conn. Close ();
}
Return themeWordDataSet;
}
A system implemented by aspnet, which now captures try catch for exceptions and records a problem
This is an exception and capture mechanism. After you capture the data at the Dal layer and throw it again, the CLR will take it as a new exception and the previous data will be overwritten. that is to say, keep the latest exception.
You can add the data of the old exception to the new exception when throwing it.