I use NLog for my application logging, every things goes right except UnhandledException. I use EventId as 1 for my other logs, for example for viewing a list. but when my application raises an unhandled exception, The produced log uses EventId 1 to show Unhandled Exception.
for better demonstration, I paste my codes here
Here is NLOG Config at nlog.config file
<target name="Initial" xsi:type="File" fileName="c:\HyperNovaLogs\${shortdate}\${level}\AppLogs-${level}_${shortdate}.log"
keepFileOpen="true"
encoding="utf-8"
archiveAboveSize ="5000000"
maxArchiveFiles="100"
layout="${newline}•LogStart${newline}
${newline} ▸Level :${uppercase:${level}}◾
${newline} ▸Date :${date:format=yyyy-MM-dd}◾
${newline} ▸Time :${time:format=HH:mm:ss.mm}◾
${newline} ▸IP :${aspnet-request-ip}◾
${newline} ▸RequestMethod :${aspnet-request-method}◾
${newline} ▸RequestUrl :${aspnet-request-url}◾
${newline} ▸ControllerName :${aspnet-mvc-controller}◾
${newline} ▸ActionName :${aspnet-mvc-action}◾
${newline} ▸RequestUserAgent :${aspnet-request-useragent}◾
${newline} ▸ResponseStatusCode :${aspnet-response-statuscode}◾
${newline} ▸UserAuthType :${aspnet-user-authtype}◾
${newline} ▸UserIdentity :${aspnet-user-identity}◾
${newline} ▸IsUserAuth :${aspnet-user-isauthenticated}◾
${newline} ▸RequestCookies :${aspnet-request-cookie}◾
${newline} ▸RequestHeaders :${aspnet-request-headers}◾
${newline} ▸MethodLocation :${callsite}◾
${newline} ▸OccuresLocation :${logger}◾
${newline} ▸EventId :${event-properties:item=EventId_Id}◾
${newline} ▸EventName :${event-properties:item=EventId_Name}◾
${newline} ▸Message :${message}◾
${newline} ▸Exceptions :${exception:format=tostring}◾${newline}
${newline}•LogEnd${newline}"/>
Here is Program.cs Config
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args).ConfigureLogging((hostingcontext, logging) =>
{
logging.AddConfiguration(hostingcontext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
logging.AddNLog();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Information);
})
.UseNLog(); // NLog: Setup NLog for Dependency injection
}
Here is the produced log example
•LogStart
▸Level :ERROR◾
▸Date :2020-04-28◾
▸Time :15:28:26.9711◾
▸IP :127.0.0.1◾
▸RequestMethod :GET◾
▸RequestUrl :http://localhost/AppUsers/ListAll◾
▸ControllerName :AppUsers◾
▸ActionName :ListAll◾
▸RequestUserAgent :Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0◾
▸ResponseStatusCode :200◾
▸UserAuthType :Identity.Application◾
▸UserIdentity :1729476546◾
▸IsUserAuth :1◾
▸RequestCookies :AAD_HyperNovaShield=CfDJ8G0KT3XSLH1GgpZLGciXkemkUFxYHlp8ER0fR9MAswI9GyRbRKRFFjkbxn0ctAobsHZgvvrEMaRqns3OBIXL9atQvz-rW2c4Ac0YMoWW0wgN6wC-pEvQuW0uWMO_z-CpiSGmK8zBtDWFkWcu6yXrjUo,AAD_HyperNovaAppAuth=CfDJ8G0KT3XSLH1GgpZLGciXkem-ToC83OMQXH59CZrCIRqTzERMAy26h7oKEX0FwqrzF0rjnAHqM3Mv--9Gjz9mxBrlDI15o9ZYxvtN2lMNPftML7c1CN93L0f3WNHCeQc0P5pym4zC9ArV0dMfNONsX4pE_1yIYe-ecroBAS-653nZBuEyRudH6RqdjOoR-7yhjJbCNvo63y7MZt7Uxn63O6Ifk8qC_ti4mE9EkiTHwJ8Hn5_uvCoJs71kT6o2fXPQ62heyPbouUCjaLuDl3XG-oG8sItDAoNvilZUSsiV-P0w52-NfAr4FAgLKSRQAJENI-7MYTXNKIdba3pz-_8rMJem4PQDysEQOqNJWJI2mHsfAHsp9CCrHWmANxWYNI-LnoaoOzJeM1EBBgjItJ_nSQHvbPhh7rDsdw87yk-zak2Yd6FwEozT406trAsfeM5AkX8X7TfZyMyls-NJfoePzvb6t_cfrJUVTH6SwGk2FXMwpb7BRio6M7vgCdjPcK2F0U3XRCMxXi-C9nnS4dZ2ARMPg09A5GOlLixLTSHJyAp_9li6d6eBD4Hg_lm_D82JrOcnLcDKYdlbdSbS8cmaha8◾
▸RequestHeaders :Connection=keep-alive,Accept=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8,Accept-Encoding=gzip, deflate,Accept-Language=en-US,en;q=0.5,Cookie=AAD_HyperNovaShield=CfDJ8G0KT3XSLH1GgpZLGciXkemkUFxYHlp8ER0fR9MAswI9GyRbRKRFFjkbxn0ctAobsHZgvvrEMaRqns3OBIXL9atQvz-rW2c4Ac0YMoWW0wgN6wC-pEvQuW0uWMO_z-CpiSGmK8zBtDWFkWcu6yXrjUo; AAD_HyperNovaAppAuth=CfDJ8G0KT3XSLH1GgpZLGciXkem-ToC83OMQXH59CZrCIRqTzERMAy26h7oKEX0FwqrzF0rjnAHqM3Mv--9Gjz9mxBrlDI15o9ZYxvtN2lMNPftML7c1CN93L0f3WNHCeQc0P5pym4zC9ArV0dMfNONsX4pE_1yIYe-ecroBAS-653nZBuEyRudH6RqdjOoR-7yhjJbCNvo63y7MZt7Uxn63O6Ifk8qC_ti4mE9EkiTHwJ8Hn5_uvCoJs71kT6o2fXPQ62heyPbouUCjaLuDl3XG-oG8sItDAoNvilZUSsiV-P0w52-NfAr4FAgLKSRQAJENI-7MYTXNKIdba3pz-_8rMJem4PQDysEQOqNJWJI2mHsfAHsp9CCrHWmANxWYNI-LnoaoOzJeM1EBBgjItJ_nSQHvbPhh7rDsdw87yk-zak2Yd6FwEozT406trAsfeM5AkX8X7TfZyMyls-NJfoePzvb6t_cfrJUVTH6SwGk2FXMwpb7BRio6M7vgCdjPcK2F0U3XRCMxXi-C9nnS4dZ2ARMPg09A5GOlLixLTSHJyAp_9li6d6eBD4Hg_lm_D82JrOcnLcDKYdlbdSbS8cmaha8,Host=localhost:8080,User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0,Upgrade-Insecure-Requests=1◾
▸MethodLocation :Microsoft.AspNetCore.Diagnostics.DiagnosticsLoggerExtensions.UnhandledException◾
▸OccuresLocation :Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware◾
▸EventId :1◾
▸EventName :UnhandledException◾
▸Message :An unhandled exception has occurred while executing the request.◾
▸Exceptions :System.InvalidOperationException: Cannot return null from an action method with a return type of 'Microsoft.AspNetCore.Mvc.IActionResult'.
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.EnsureActionResultNotNull(ObjectMethodExecutor executor, IActionResult actionResult)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)◾
•LogEnd
What I want is changing this default EventId as 1 for UnhandledException. Actually, the question is: How can I change default EventIds ?
Maybe replace this:
${event-properties:item=EventId_Id}
With this:
${when:when='${event-properties:item=EventId_Name}'=='UnhandledException':inner=42:else=${event-properties:item=EventId_Id}}
It will now print EventId=42 for UnhandledException
. See also https://github.com/nlog/NLog/wiki/When-Layout-Renderer