Sknecht
Sknecht

Reputation: 1074

Exclude custom Exception class from logging in Asp.net core

Is there a way that I can exclude a custom Exception class from the logging system? I know I can filter out by Category but I would like just to keep one self-made exception class out.

Upvotes: 2

Views: 859

Answers (1)

Jann Westermann
Jann Westermann

Reputation: 401

I don't see a way with the built-in filters. But you could use NLog with the ASP.NET Core logging system. You're writing the log messages the same way as before, but it provides you a wider range of configuration, including a way to filter specific exception types.

Sample

Let's create a nlog.config with two target log files: one with all messages, including the unwanted exception type and one without this type:

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

The exclusion of the unwanted exception types is configured within the logging rules. In this example, we're filtering the exception type SampleApplication.Exceptions.SampleException:

<rules>
  <logger name="*" minlevel="Trace" writeTo="all" />
  <logger name="*" minlevel="Trace" writeTo="filtered">
    <filters>
      <when condition="contains('${exception:format=Type}', 'SampleApplication.Exceptions.SampleException')" 
            action="Ignore" />
    </filters>
  </logger>
</rules>

Upvotes: 2

Related Questions