How to log error detail in nlog with custom error handling in asp.net?

Raj
Raj
648 Points
26 Posts

I have asp.net mvc application with custom error pages:

<customErrors mode="On" defaultRedirect="Error/SomethingGoingWrong">
  <error statusCode="500" redirect="Error/SomethingGoingWrong" />
  <error statusCode="404" redirect="Error/PageNotFound" />
</customErrors>

Cusom error pages are working fine. But I want to log error trace throw nlog and trying something in error action:

public class ErrorController : Controller
{
    public ActionResult Error()
    {
        var ex = Server.GetLastError();
        logger.Fatal(ex, $"{ex?.Message}");
        ......
    }
}

But always getting ex=null.

Views: 2493
Total Answered: 2
Total Marked As Answer: 1
Posted On: 08-Jun-2020 03:30

Share:   fb twitter linkedin
Answers
Brian
Brian
2376 Points
13 Posts
         

I think, you can use redirectMode="ResponseRewrite" as 

<customErrors mode="On" defaultRedirect="Error/SomethingGoingWrong" redirectMode="ResponseRewrite">
  <error statusCode="500" redirect="Error/SomethingGoingWrong" />
  <error statusCode="404" redirect="Error/PageNotFound" />
</customErrors>
Posted On: 12-Jun-2020 22:35
Rashmi
Rashmi
1068 Points
19 Posts
         

We use Global.aspx.cs to log all kind error as:

void Application_Error(object sender, EventArgs e)
{
    var _logger = LogManager.GetCurrentClassLogger();
    var ex = HttpContext.Current.Server.GetLastError();
    _logger.Fatal(ex, $"{ex?.Message}");
}
Posted On: 12-Jun-2020 22:42
 Log In to Chat