Since the log is very important now, but where to write the log is better, I chose to be in global, the error code on the net, rather than write a large number of Try catch at the bottom and then write the log in the catch, the write log in each catch will avoid a lot of duplicate code. Of course this is currently a method we take, and we can propose a better way to manage the log, and below I begin to write code
The first step: try to get rid of the project try catch. Look at the code.
Private void Exceptiontestone () { int1; int 0 ; int c = A/b; }
The above code throws an exception
The second step: If you must use try catch in the project, because sometimes when we connect to WCF, if there is an exception when we need to close the connection to avoid clogging, then we take the exception method
Private voidExceptiontesttwo () {Try{List<Simple> Simples =NULL; Simples. ADD (NewSimple () {Name ="An exception occurred" }); } Catch(Exception ex) {Throw NewException ("", ex); } }
Step Three: We create a new global.asax in the Application_Error to join the exception information in the queue as follows
// Create a static queue record put the exception in the queue Private Static New Queue<exception>(); protected void Application_Error (object sender, EventArgs e) { = server.getlasterror (); if NULL ) { queue. Enqueue (exp); } Server.ClearError (); }
Fourth Step: Exception information added to the log (here for the sake of simple write txt text)
protected voidApplication_Start (Objectsender, EventArgs e) {ThreadPool.QueueUserWorkItem (a= { while(true) { Try { if(Queue. Count >0) {Exception ex=queue. Dequeue (); Writelog (ex); } Else{System.Threading.Thread.Sleep (Timespan.fromseconds (3)); } } Catch(Exception ex) {
Writelog (ex);
} } }); }
Private voidWritelog (Exception ex) {if(! File.exists (@"e:\c# Series \exceptiondealwith\exceptiondealwith\log.txt") {FileStream FS1=NewFileStream (@"e:\c# Series \exceptiondealwith\exceptiondealwith\log.txt", FileMode.Create, FileAccess.Write);//Create write FileStreamWriter SW =NewStreamWriter (FS1); Sw. WriteLine (ex. Message);//Start Write ValueSW. Close (); FS1. Close (); } Else{StreamWriter SR= File.appendtext (@"e:\c# Series \exceptiondealwith\exceptiondealwith\log.txt"); Sr. WriteLine (ex. Message); Sr. Close (); } }
Of course the access error message you can define more than a few metaphor IP address, stack information errors and so on basic is so much. This is the basic idea. With the logs, I'll be able to query the log log information based on time, IP, etc.
Download
Catch exception in Global