We implement here in just 5 minutes an error events log , monitoring and troubleshooting messages from your MVC application to the windows Events Viewer. This way, all errors will be preserved to the windows events log.
Also we set a custom error page for your MVC app, so that the users can see an appropriate error page:
Step by step How to Log MVC troubleshooting and error messages to the Events Viewer
First, let's type some error in the code, something like dividing by zero:
Throw again the error by browsing to the MVC View, and open the "Application" tab at the Event Log:
The thousands of events should be sorted by "Date and Time", and you should see your last error at the top of the list:
Happy programming.....
by Carmel Schvartzman
Rebuild and run your app, and browse to the MVC View corresponding to the Controller you chose:
OK, we have the Exception and an YSOD typical page ("Yellow Screen Of Death").
First, we cannot allow users to see this screen, so let's change the settings at the web.config file:
Inside the <system.web> element , add a <customErrors> and set the "mode" to "On" or "RemoteOnly", saying that a custom error page will be shown to remote users or to everyone.
Browse again to see the error:
OK, now the users don't see the YSOD page.
Now, let's log the errors to the Windows Event Viewer, by adding an Application_Error event handler to the Global.asax file:
Here we instantiate an EventLog object with the following information:
1) the URL where the exception was thrown: we get this from the Request.Path variable
2) the Exception Message and info: this we get from the Server.GetLastError() method
3) we set the "Source" of the error as "Application"
4) the Error Type will be EventLogEntryType.Error
Save and build the project. Open the Event Viewer:
Throw again the error by browsing to the MVC View, and open the "Application" tab at the Event Log:
The thousands of events should be sorted by "Date and Time", and you should see your last error at the top of the list:
Double click the error to see its details:
There you can see the URL and the error message, even the line where the exception was thrown.
We hope that this article has helped you ..
Happy programming.....
by Carmel Schvartzman
כתב: כרמל שוורצמן
No comments:
Post a Comment