Gicu Mironica
Gicu Mironica

Reputation: 635

C# - Log custom exceptions with NLog

I am trying to configure NLog to log my own exceptions and system exceptions into 2 different log files.
Let's say when I run _logger.LogError("This is my exception."), it should be logged to myerrors.log, but when the server crashes, the error should be logged to a different file.

The problem I have now is that, the system errors are logged into both files.
This is my nlog.config file:

<?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"
      autoReload="true"
      internalLogLevel="Info"
      internalLogFile=".\SystemLogs\internal-nlog.txt">

  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file  -->
    <target xsi:type="File" name="allfile" fileName=".\SystemLogs\nlog-all-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

    <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
    <target xsi:type="File" name="ownFile-web" fileName=".\ErrorLogs\${shortdate}\errors-${shortdate}.log"
            layout="${longdate}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--Skip non-critical Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" maxlevel="Info" final="true" />
    <!-- BlackHole without writeTo -->
    <logger name="*" minlevel="Error" writeTo="ownFile-web" />
  </rules>
</nlog>


Here is the appsettings.json config:

"Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Error",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }

Upvotes: 2

Views: 3494

Answers (1)

Kishan Vaishnav
Kishan Vaishnav

Reputation: 2631

First, you need to configure a Global Exception handling mechanism which would handle any unhandled exception.

In .Net Core, you can do that by creating a middleware refer link.

public class ExceptionMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<ExceptionMiddleware> _logger;

    public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
    {
        _logger = logger;
        _next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        try
        {
            await _next(httpContext);
        }
        catch (Exception ex)
        {
            _logger.Error(ex);
            await HandleExceptionAsync(httpContext, ex);
        }
    }

    private Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

        ApiResponse<object> response = new ApiResponse<object>(exception, EResponseCode.GlobalException, exception.Message, null);

        string responseString = JsonConvert.SerializeObject(response);
        return context.Response.WriteAsync(responseString);
    }
}

Then, register it in Startup.cs by app.UseMiddleware<ExceptionMiddleware>();

Create a target named globalErrors.

<target xsi:type="File" name="globalErrors" fileName="\globalErrors.log"
        layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

Configure logs coming from the middleware.

<logger name="*.ExceptionMiddleware" writeTo="globalErrors" />

Upvotes: 2

Related Questions