Reputation: 682
In my ASP.NET MVC project I have an action with [LogErrors] attribute as below:
[LogErrors]
public ActionResult Index()
{
var i = 0;
var c = 10 / i;
return View();
}
I made an aunhandled exception without trycatch(devide 10 by 0) in this action and I must log this exception error text and else log in which action this exception happened in a text file with NLog. I made the [LogErrors] as below:
public class LogErrorsAttribute : FilterAttribute, IExceptionFilter
{
void IExceptionFilter.OnException(ExceptionContext filterContext)
{
if (filterContext != null && filterContext.Exception != null)
{
string controller = filterContext.RouteData.Values["controller"].ToString();
string action = filterContext.RouteData.Values["action"].ToString();
string loggerName = string.Format("{0}Controller.{1}", controller, action);
NLog.LogManager.GetLogger(loggerName).Error(string.Empty, filterContext.Exception);
}
}
}
and my NLog.config is as below:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" >
<targets>
<target name="file" xsi:type="File" fileName="C:\Logs\${shortdate}.log"
layout="
--------------------- ${level} (${longdate}) ----------------------${newline}
IP: ${aspnet-request-ip}${newline}
Call Site: ${callsite}${newline}
${level} message: ${message}${newline}
Id: ${activityid}${newline}
aspnet-sessionid: ${aspnet-sessionid}${newline}
aspnet-request-method: ${aspnet-request-method}${newline}
aspnet-request-host: ${aspnet-request-host}${newline}
aspnet-request-form: ${aspnet-request-form}${newline}
aspnet-request-cookie: ${aspnet-request-cookie}${newline}
aspnet-request: ${aspnet-request:serverVariable=HTTP_URL}${aspnet-request:queryString}${newline}
aspnet-mvc-controller: ${aspnet-mvc-controller}${newline}
aspnet-mvc-action: ${aspnet-mvc-action}${newline}
aspnet-appbasepath: ${aspnet-appbasepath}${newline}
" encoding="UTF8"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="file" />
</rules>
</nlog>
How fix my configs to log this exception error text and else log that in which action this exception happened in a text file? Any help will be appriciated!
Upvotes: 2
Views: 1369
Reputation: 36700
You need to send a message to .Error
and send the Exception
as first parameter.
Otherwise it roughly translated to string.Format("", filterContext.Exception)
.
So something like this:
NLog.LogManager.GetLogger(loggerName)
.Error(filterContext.Exception, "Unhandled exception in controller");
If that isn't working, then please check the NLog troubleshooting guide
Upvotes: 1