Java has log4j to record error logs, while asp.net can write a log to record errors by itself!
- Encapsulate a class first
using System;using System.Collections.Generic;using System.Linq;using System.Web;
Using System. IO; using System. globalization; // <summary> // ErrHandler error log processing class /// </summary> public class ErrHandler {public ErrHandler () {// TODO: add constructor logic here //} public static void WriteError (Exception e) {try {// error log record address [generate a log file every day] string path = "~ /Error/"+ DateTime. Today. ToString (" dd-MM-yy ") +". log "; if (! File. exists (System. web. httpContext. current. server. mapPath (path) {// if this log does not exist, File is created. create (System. web. httpContext. current. server. mapPath (path )). close ();} // write the log record using (StreamWriter w = File. appendText (System. web. httpContext. current. server. mapPath (path) {w. writeLine ("Error Recode:"); w. writeLine ("\ tError Time: {0}", DateTime. now. toString (CultureInfo. invariantCulture); w. writeLine ("\ tError Address:" + System. web. httpContext. current. request. url. toString (); w. writeLine ("\ tTargetSite:" + e. targetSite); w. writeLine ("\ tError Message:" + e. message); w. writeLine ("\ tError HelpLink:" + e. helpLink); w. writeLine ("\ tError StackTrace:" + e. stackTrace); w. writeLine ("************************************* **************************************** *******"); w. writeLine ("\ r \ n"); w. flush (); w. close () ;}} catch (Exception ex) {WriteError (ex );}}}
2. The class has been written! Where can I call it? Create a Global. asax file!
<% @ Application Language = "C #" %> <script runat = "server"> void Application_Start (object sender, EventArgs e) {// Code that runs on application startup} void Application_End (object sender, EventArgs e) {// Code that runs on application shutdown} void Application_Error (object sender, EventArgs e) {// get the final error Exception objErr = Server. getLastError (). getBaseException (); // record ErrHandler. writeError (objErr );
// Clear the previous error
Server.ClearError(); } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started } void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. } </script>
In this way, once an error occurs, it will be recorded in the log! You only need to regularly check the error log.
Of course, you can also record the error, such:
try { throw new Exception("Error"); } catch (Exception ex) { ErrHandler.WriteError(ex); }
OVER
Technorati label: asp.net, error