Logging with nlog
-> Install the Nugget package
-> Create a config file with [Link] file
-> mentioned target name and level of logging in rules
-> Enable copy to bin folder
-> Add nlog extenstion method as logging providers to the project
LogLevel based on severity:
- Trace = 0 //Capture all the logs from trace to Critical
- Debug = 1
- Information = 2
- Warning = 3
- Error = 4
- Critical =5
- None = 6
- [Link]() //To log trace message
- [Link]() //To log Debug message
- [Link]() //To log Information message
- [Link]() //To log Warning message
- [Link]() //To log Error message
- [Link]() //To log Critical message
Exception & its methods in MVC
- If exception is handled in your application then it must be configured inside the
Application_Error(Object sender, EventArgs e) method
- All controller level - protected override void OnException(ExceptionContext filterContext)
- We can also create our own Exception Handler by inheriting from HandleErrorAttribute as in
the following:
Eg:
[myExceptionhandler]
controller name{ //some code; }
public class MyExceptionHandler : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
Exception below properties & methods:
- Source
- HelpLink
- StackTrace // Actual Error
- TargetSite
- InnerException // Origin Exception
- Message
- GetBaseException()
-> Use below method to log the error
- [Link]();
- [Link]( [Link].
GetCurrentMethod().DeclaringType)
- [Link]([Link], exception) //To log the error
-> use [Link] class to write Log on text file.
Types of Errors:
- Debug
- Info
- Error
- Fatal
Method to log the error to Event Viewer:
private static void LogToEventViewer(string log)
{
if ([Link]("[Link]"))
{
// Create an instance of the eventlog
EventLog eventLog = new EventLog("PragimTech");
// set the source for the eventlog
[Link] = "[Link]";
// Write the exception details to the event log as an error
[Link](log, [Link]);
}
}
Error handling in [Link] Core
-> 404 error example in [Link] Core:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if ([Link]())
{
[Link]();
}
[Link]();
[Link](routes =>
{
[Link]("default", "{controller=Home}/{action=Index}/{id?}");
});
}
-> With the following line in place, if there is a 404 error, the user is redirected to /Error/404. The
placeholder {0}, in "/Error/{0}" will automatically receive the http status code.
Eg:
[Link]("/Error/{0}");