On partial content-error handling mechanism of aspect-oriented programming

Source: Internet
Author: User
Tags log4net

Error handling mechanism.

Faced with multiple Web servers, multithreading, we want to log the error message into a TXT document.

But writing the error message to memory is fast. Writing to the hard disk has a bunch of problems. such as slow reading and writing, concurrency problems.

Today we're using this implementation error handling this article with MVC as an example

1, the first to be in the golable file protected void Application_Start ()

Registers an error handling mechanism.

Bring a filter in MVC

Filterconfig.registerglobalfilters (globalfilters.filters);

This is where we see this filter.

2, in fact, is in the App_start folder under the FilterConfig.cs file

3. Open FilterConfig.cs File

A registration event was written. We can see that this is a mechanism for error handling.

(Of course, what you see is the Handleerrorattribute Class)

4, so you may find it strange, let's look at the definition of myexceptionattribut.

Inherited the Handleerrorattribute.

Here, I'll post this code for this class.

public class Myexceptionattribute:handleerrorattribute
{
private static Object obj = new Object ();
public static concurrentqueue<exception> Exceptionqueue = new concurrentqueue<exception> ();//define Queue

<summary>
The exception is caught in the method.
</summary>
<param name= "Filtercontext" ></param>
public override void Onexception (Exceptioncontext filtercontext)
{

Base. Onexception (Filtercontext);
Exception ex = filtercontext.exception;//captures exception information.
Writes exception information to the queue.
Exceptionqueue.enqueue (ex);
Jump to the error page.
FilterContext.HttpContext.Response.Redirect ("/error.html");

}
}

The main is to define a static queue Concurrentqueue

(You can also use Queue, of course.) But Microsoft says the concurrentqueue is safer than the Queue. It seems to be thread-safe, a heap of theories, and, frankly, more secure with concurrentqueue.

So all the errors are in this queue. (that is, memory)

That's not always possible. The memory power is gone.

So we want to save the data to the hard drive.

5, now again in

golable file protected void Application_Start ()

Registering a consumer thread (which is explained later, and then continues) is the addition of the Code in protected void Application_Start (), preferably at the front.

The content is that the thread pool opens up one of the threads from the exceptionqueue queue of the myexceptionattribute that was just defined.

Add the error message to the back of the file. If the queue is empty, the thread stays for 3 seconds.

String filePath = Server.MapPath ("/log/");
ThreadPool.QueueUserWorkItem ((a) =
{

while (true)//NOTE: The thread cannot end. Data that is written to the queue cannot be processed.
{

Here you can add an if (MyExceptionAttribute.ExceptionQueue.Count () > 0)
{Send mail to admin}
if (MyExceptionAttribute.ExceptionQueue.Count () > 0)
{
Exception ex= MyExceptionAttribute.ExceptionQueue.Dequeue ();//extract data from the queue.
Exception ex = null;
BOOL Isresult = MyExceptionAttribute.ExceptionQueue.TryDequeue (out ex);
if (ex! = null && isresult)
{
String FullPath = FilePath + DateTime.Now.ToString ("yyyy-mm-dd") + ". txt";
File.appendalltext (FullPath, ex. ToString ());
ILog logger = Logmanager.getlogger ("errormsg");
Logger. Error (ex. ToString ());
}
Else
{
Thread.Sleep (3000);
}
}
Else
{
Thread.Sleep (3000);//Avoid causing the CPU to spin.
}
}

}, FilePath);

6, summary.

This is the model of a producer consumer.

Producers are the source of errors. The consumer is the way to register to save the log.

There is a warehouse in the middle that is the static error queue.

You can see that the system-generated errors are temporarily stored in memory. Then a new thread goes to read and write the static error queue.

The normal situation needs to be in the error queue to add an error queue number greater than 1000 when the warning to the mailbox function. That feels a bit complicated, after all, it's just about error handling.

7. Log4net an open source framework I've talked about earlier is a good record error.

Here is a connection log4net configuration method you can put that together and get here. Then there will be

Add code to protected void Application_Start ()

Change to. Notice is changed to:

Log4net. Config.XmlConfigurator.Configure ();
Start a thread, view the exception queue
String filePath = Server.MapPath ("/log/");
ThreadPool.QueueUserWorkItem ((a) =
{

while (true)//NOTE: The thread cannot end. Data that is written to the queue cannot be processed.
{
if (MyExceptionAttribute.ExceptionQueue.Count () > 0)
{
Exception ex= MyExceptionAttribute.ExceptionQueue.Dequeue ();//extract data from the queue.
Exception ex = null;
BOOL Isresult = MyExceptionAttribute.ExceptionQueue.TryDequeue (out ex);
if (ex! = null && isresult)
{
String FullPath = FilePath + DateTime.Now.ToString ("yyyy-mm-dd") + ". txt";
File.appendalltext (FullPath, ex. ToString ());
ILog logger = Logmanager.getlogger ("errormsg");
Logger. Error (ex. ToString ());
}
Else
{
Thread.Sleep (3000);
}
}
Else
{
Thread.Sleep (3000);//Avoid causing the CPU to spin.
}
}

}, FilePath);

This will record the error log as you requested.

Under the App_Data folder. (If you have an unhandled error.) Oh

See, it worked.

Off Topic (

Do not create a var s=3/0;

That's all you can do.

On partial content-error handling mechanism of aspect-oriented programming

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.