Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
/NLogPublic

Configure from code

Rolf Kristensen edited this pageJan 23, 2025 ·31 revisions

NLog can be also configured programmatically.

All options match with the attribute names in the XML config, so for all config options you could checkhttps://nlog-project.org/config/

There is also a SHFB docs, seehttps://nlog-project.org/documentation/

Fluent API Example

NLog 5.0 introduces aFluent-Configuration-API so you can do this instead:

NLog.LogManager.Setup().LoadConfiguration(builder=>{builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteToConsole();builder.ForLogger().FilterMinLevel(LogLevel.Debug).WriteToFile(fileName:"file.txt");});

Simple Example

varconfig=newNLog.Config.LoggingConfiguration();// Targets where to log to: File and Consolevarlogfile=newNLog.Targets.FileTarget("logfile"){FileName="file.txt"};varlogconsole=newNLog.Targets.ConsoleTarget("logconsole");// Rules for mapping loggers to targetsconfig.AddRule(LogLevel.Info,LogLevel.Fatal,logconsole);config.AddRule(LogLevel.Debug,LogLevel.Fatal,logfile);// Apply configNLog.LogManager.Configuration=config;

Extended Features

Passing Custom Values

There are many ways to capture currentContext and output it to the final target. Simple example:

logger.Info("Message with {myProperty}","myValue");

Render with${event-properties:myProperty}

Add this to Layout, e.g.

varfileTarget=newFileTarget("target2"){FileName="${basedir}/file.txt",Layout="${longdate} ${level} ${message}  ${exception} ${event-properties:myProperty}"};

For many more examples, see${event-properties} layout renderer.

Creating dynamic Layouts

NLog Layout will implicitly convert from string-objects. It will automatically parse the string and compile it into the recognizedLayout-Renderers.

NLog will perform validation when parsing, but errors detected will be swallowed unless having enabledLogManager.ThrowConfigExceptions. But one can also force NLog to throw parsing error no matter what:

varlayout=NLog.Layouts.Layout.FromString("${evil}",throwConfigExceptions:true);// will throw

NLog 4.7 also allows you to generate a Layout from a simple lambda-method:

varunixTime=NLog.Layouts.Layout.FromMethod(logEvent=>((DateTimeOffset)logEvent.TimeStamp).ToUnixTimeSeconds().ToString());varjsonLayout=NLog.Layouts.JsonLayout(){Attributes={newNLog.Layouts.JsonAttribute("unixtime",unixTime){Encode=false}}};

!! NOTICE !! Ensure that custom method given toLayout.FromMethod is very simple. Deadlock or StackOverflow can occur if performing complex logic that triggers new logevents or acquiring locks.

Update config in code

It is possible to dive into the NLogLoggingConfiguration and assign properties directly. But NLog is much happier about usingNLog Layout logic when possible. Example:

<targettype="file"name="logfile"filename="${gdc:CompanyName:whenEmpty=Default}_${shortdate}.log" />

Then in code one can just update theGDC-item, and it will take effect right away:

NLog.GlobalDiagnosticsContext.Set("CompanyName","SuperPower");

This removes the need to know the exact NLog-target names in the NLog.config, so it decouples the logic even further and makes it more resilient. This will also work excellent together withautoReload="true", as you don't have to re-apply the same settings again, as it will happen automatically. This can also be used foradjusting logging rules dynamically at runtime.

But if you really want to get your hands dirty, then here you go:

varconfiguration=LogManager.Configuration;// Update single targetvarmyFileTarget=configuration.FindTargetByName<FileTarget>("myTargetName");if(myFileTarget!=null)myFileTarget.FileName="SuperPower"+"_${shortdate}.log";LogManager.Configuration=configuration;// re-init// Update all targetsforeach(varfileTarget= configuration.AllTargets.OfType<FileTarget>()){fileTarget.FileName="SuperPower"+"_${shortdate}.log";}LogManager.Configuration=configuration;// re-init

Combine nlog.config and config from code

Please note that combining the config file (nlog.config) and changing it in code, the reload of nlog.config could undo your changes. If you combine both, then reapply the changes on the reload event. E.g.

// On start of your programUpdateConfig();LogManager.ConfigurationChanged+=(sender,e)=>{if(e.ActivatedConfiguration!=null){//Re apply if config reloadedUpdateConfig();}};

WhereUpdateConfig is

publicvoidUpdateConfig(){// Do NOT set LogManager.Configuration because that will cause recursion and stackoverflowvarfileTarget=LogManager.Configuration.FindTargetByName<FileTarget>("myTargetName");fileTarget.FileName="${basedir}/file.log";LogManager.ReconfigExistingLoggers();// Soft refresh}

Instead of trying to perform patching of NLog-configuration, then it is recommended to make use ofNLog Layouts for Target- andLoggingRule-configuration forexample using${gdc}

-Troubleshooting Guide - See available NLog Targets and Layouts:https://nlog-project.org/config

Configuration

Programmatic Configuration

Advanced

Extending NLog

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp