Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create a named logger with NLog and filter logging by this name(s)?

Tags:

c#

.net

nlog

Sometimes I don't want to log everything especially to the Visual Studio Output window (target --> debugger) during development. I thought maybe there is a way to name a particular logger (one class) or few loggers (from multiple classes) so that in the configuration file I can enable logging only for the classes in development that I am interested in at the moment.

Currently I have this most common NLog line in all my classes:

private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

and a very standard configuration that just renders logs to the output window.

Unfortunately I had no luck in finding how to enable/disable loggers by class(es).

like image 509
t3chb0t Avatar asked Sep 29 '22 13:09

t3chb0t


1 Answers

As I've mentioned in the comments, you could use the NLog Conditions to evaluate and determine what you want to do with the results. As the documentation says:

Conditions are filter expressions used with the when filter. They consist of one or more tests. They >are used in the when filter to determine if an action will be taken.

Also there's a very useful example:

<rules>
    <logger name="*" writeTo="file">
        <filters>
            <when condition="length('${message}') > 100" action="Ignore" />
            <when condition="equals('${logger}','MyApps.SomeClass')" action="Ignore" />
            <when condition="(level >= LogLevel.Debug and contains('${message}','PleaseDontLogThis')) or level==LogLevel.Warn" action="Ignore" />
            <when condition="not starts-with('${message}','PleaseLogThis')" action="Ignore" />
        </filters>
    </logger>
</rules>
like image 62
elvin Avatar answered Nov 09 '22 13:11

elvin