Talk about exception handling and log tracking in ASP.

Source: Internet
Author: User
Tags stack trace log4net

About the handling of exceptions presumably everyone knows Try{}catch () {}finally{}, which is no longer spoken. With the "Debug"-"Exception" in VS, the common Language Runtime exceptions bar in the pop-up exception dialog is the exception hierarchy in. Net.

Custom Exceptions:

You can create custom exception classes if the system-provided exception classes are no longer sufficient to meet the needs of application development, or if the development team needs a set of custom exception handling mechanisms. The custom exception class should inherit from the ApplicationException class directly, and it is best to have a good name: the wrong descriptive name +exception, you should define 3 constructors: The default constructor, the constructor that accepts the error message, The constructor that accepts the error message and the inner exception object. Exceptions thrown by the CLR inherit from SystemException, and the exception that the application throws should inherit from ApplicationException. In this way, developers can write catch blocks to catch all exceptions thrown by the CLR or exceptions thrown by all applications.

Anderslly Recommended Shineqiujuan

Log Exceptions:

Web applications may have thousands of users, and sometimes they may need to be logged in addition to displaying an error message to the user, such as a Web server that is overloaded, several problems intermittently occurring, and so on. The NET Framework provides a variety of logging tools, such as the ability to send e-mail when errors occur, to add to database records or to read and write files. A good way to handle this is with Windows events, a Windows event program that is built into a Windows system to record system or application logs, and can be used by any application.

Open Event Viewer in the Admin tool in Control Panel to view the Windows event log. Generic event classifications have applications (used to log errors or notifications from any application, which can typically be logged in an ASP. NET application Exception) system (used to record operating system-related events) security (for logging security-related issues, used only by the operating system). Clicking an event in these event categories will bring up the details window for that event. Right-click on these event categories to clear the log, save the log, new log view, open from the file, through the properties can set the maximum size of the log file, and so on. If the log size exceeds the specified limit, the expired event log is automatically purged.

To write an exception to the Windows event log

The EventLog class under the System.Diagnostics namespace can read and write event logs

protected void Button1_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/>"; Incorrect description information

Label1.Text + = "<b> error source:</b>" + ex.     Source + "<br/>"; Which assembly was returned with an error

Label1.Text + = "<b> stack trace:</b>" + ex. StackTrace;

Label1.forecolor = System.Drawing.Color.Red;

To determine if there are any such events in the Windows event log, we can see in the event log that each event has an event ID, and events of the same event ID belong to the same class of events

if (! EventLog.SourceExists ("Division operation Error"))

{

If no such event exists, register the event and register the event in our custom event class, the second parameter defaults to the application

EventLog.CreateEventSource ("Division Operation Error", "ASPNET event log");

}

The constructor of the EventLog class can open a specified event class (equivalent to a table)

EventLog Elog = new EventLog ("ASPNET event log");

Specifies the event source string that will appear in the source column of the event category (equivalent to the source field)

Elog. Source = "from Web server";

Writes an event entry to the specified event class, where event description, event type, event ID, and so on (equivalent to a record) are specified

Elog. WriteEntry (ex. Message, EventLogEntryType.Error);

}

}

You can see that the Windows event log is like a database, and the event class is a different table, and the event entry is the record

Programmatic viewing of event logs (equivalent to viewing all records of a table in a database)

Complex, specifying the fields that are displayed

Create an event item entity class first

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;

}

}

Then create a list class to hold all the event items in an event category

public class Eventlist:list<eventitem>

{

Public EventList (String logname)

{

if (! EventLog.Exists (logname)) Determine if there is a classification of the event (whether there is a table)

{

Return

}

Else

{

EventLog Elog = new EventLog (logname); Open an event category

foreach (EventLogEntry item in Elog. Entries) Event entry is EventLogEntry type, Entries property gets all the event entries in the event category

{

Eventitem Eventitem = new Eventitem (item. Entrytype.tostring (), item. Message, item. TimeGenerated, item. Source);

This. ADD (Eventitem);

}

}

}

}

protected void Button1_Click (object sender, EventArgs e)

{

string logname = TextBox1.Text;

EventList eventlist = new EventList (logname);

Gridview1.datasource = EventList;

}

Simple, gets the event item that contains the default field

protected void Button1_Click (object sender, EventArgs e)

{

string logname = TextBox1.Text;

EventLog Elog = new EventLog (logname);

Gridview1.datasource = Elog.  Entries; The Entries property returns a collection type of 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 the way to generate a txt log file every day, the other way is described in the first link, the second link theory is very good

<log4net>

<root>

<appender-ref 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] Error description [%message]"/>

</layout>

</appender>

</log4net>

Page tracking

Although the error pages of ASP. NET provide very useful information, sometimes developers need more detailed information to correct errors in the application. For example, the application executes a property or traces a logic error in the application. Sometimes the application may produce some invalid data, but there is no obvious exception trigger. Asp. NET provides tracking capabilities that allow developers to report diagnostic information in a more convenient and resilient way.

Enabled at the page level in addition to the <%@ page trace= "true"%> setting, you can also set it in code such as:

protected void Page_Load (Object Sender,eventargs e)

{page.trace.isenabled=true;}

The trace property of the Page object is an instance of the System.Web.TraceContext class. The advantage of using code is that you can enable and disable page tracking based on a specific environment.

This provides a lot of diagnostic information after running asp:

1. Request details (SessionID, request type, request time, request status code, request encoding, response encoding)

2. Tracking information (tracking information shows the process flow of the page before the page is sent to the client and provides a detailed execution time for the page execution)

3. Control tree (displays all Runat=server controls on the page)

4. Session State and application state (displays key, value, type, and all application state application keys, values, types) for all session state sessions in the current application

5. Request Cookie Collection (the name, value, size of the cookie requested by the Web browser) Response cookie collection (name, value, size of the cookies sent by the Web server)

6. Header collection (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, languages used, etc.)

7. Response header Collection (lists some of the information sent to the client as a response)

8. Form collection (form information submitted by post) but it looks like 8, 9 is the value of the server control in the form (ASP. NET page trace tracking only server controls?)

9.Querystring Collection (the name and value in the form information/query string submitted by Get method)

10. Server variables (usually not seen)

The above is only for a page use tracking, can be set in the root Web. config, the entire application start tracking, under <system.web> configuration:

<system.web>

<trace enabled= "true" requestlimit= "pageoutput=" false "tracemode=" SortByTime "localonly=" true "/>

</system.web>

REQUESTLIMIT (tracking information for the maximum number of HTTP requests) TraceMode (sorted by how) localonly (tracking information only appears locally)

Access to these request information is only possible by accessing the trace.axd (which does not actually exist) under the root directory.

Yes, everyone is talking about the website of the program life, I also recommend it.

Related Article

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.