GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Fluent Configuration API

Fluent Configuration API

Jump to bottom Edit New page
Rolf Kristensen edited this page Jul 18, 2026 · 19 revisions

The NLog Fluent Configuration API allows you to configure NLog directly in C# instead of XML.

  • No XML required. No separate configuration file required.
  • Explicit setup logging as part of application startup
  • Compile-time checking
  • Full access to NLog features
  • Allow building reusable components or libraries with addtional NLog extensions.

The NLog LogFactory has support for fluent setup of the initial NLog configuration:

  • LoadConfiguration - Explicit build/adjust NLog config. Introduced with NLog 4.7 but heavily improved with NLog 5.0
  • SetupExtensions - Registration of NLog extensions before loading configuration. Introduced with NLog 4.7
  • SetupSerialization - Override default log output for specific object types. Introduced with NLog 4.7
  • SetupLogFactory - LogFactory specific options. Introduced with NLog 5.0
  • SetupInternalLogger - InternalLogger specific options. Introduced with NLog 4.7
  • LoadConfigurationFromFile - For loading NLog config from specific xml file. Introduced with NLog 4.7
  • LoadConfigurationFromXml - For loading NLog config from xml content. Introduced with NLog 4.7

Example with LoadConfiguration

Build NLog config that writes everything to console:

NLog.LogManager.Setup().LoadConfiguration(builder => {
   builder.ForLogger().WriteToConsole()
});

Build NLog config that writes to file and console:

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

Build NLog config that writes to custom target::

NLog.LogManager.Setup().LoadConfiguration(builder => {
   builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteTo(new MyCustomTarget() { Layout = "${message}" });
});

Build NLog config that restricts output from noisy logger:

NLog.LogManager.Setup().LoadConfiguration(builder => {
   builder.ForLogger("Microsoft.*").WriteToNil(finalMinLevel: LogLevel.Warn);
   builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteToConsole();
});

Example with SetupExtensions

To register a custom LayoutRenderer:

NLog.LogManager.Setup().SetupExtensions(ext =>
   ext.RegisterLayoutRenderer("trace_id", (logevent) => CorrelationIdentifier.TraceId.ToString())
);

To register a custom Target:

NLog.LogManager.Setup().SetupExtensions(ext =>
   ext.RegisterTarget<MyNamespace.MyFirstTarget>("MyFirst")
);

Example with SetupSerialization

Override the default object reflection for System.Net.WebException:

NLog.LogManager.Setup().SetupSerialization(s =>
   s.RegisterObjectTransformation<System.Net.WebException>(ex => new {
      Type = ex.GetType().ToString(),
      Message = ex.Message,
      StackTrace = ex.StackTrace,
      Source = ex.Source,
      InnerException = ex.InnerException,
      Status = ex.Status,
      Response = ex.Response.ToString(),  // Call your custom method to render stream as string
   })
);

Skip default object reflection for ReadOnlyMemory<byte>:

NLog.LogManager.Setup().SetupSerialization(s =>
   s.RegisterObjectTransformation<ReadOnlyMemory<byte>>(obj => obj.Length)
);

Examples with SetupLogFactory

Explicit configure the global NLog TimeSource:

NLog.LogManager.Setup().SetupLogFactory(fac =>
   fac.SetTimeSourcAccurateUtc()
);

Explicit activate exceptions on configuration errors:

NLog.LogManager.Setup().SetupLogFactory(fac =>
   fac.SetThrowConfigExceptions(true)
);

Explicit configure the global LogLevel threshold:

NLog.LogManager.Setup().SetupLogFactory(fac =>
   fac.SetGlobalThreshold(LogLevel.Info)
);

Example with SetupInternalLogger

Write internal warnings and errors to console output:

NLog.LogManager.Setup().SetupExtensions(intern =>
   intern.SetMinimumLogLevel(LogLevel.Warn).LogToConsole(true)
);

Register event handler to be called on warnings and errors:

NLog.LogManager.Setup().SetupExtensions(intern =>
   intern.SetMinimumLogLevel(LogLevel.Warn).AddLogSubscription((sender, evt) => ReportEvent(evt.Message))
);

Example with LoadConfigurationFromAppSettings

Loads NLog config from appsettings.json (with fallback to NLog.confg) and requires NLog.Web.AspNetCore:

var logger = LogManager.Setup()
                       .LoadConfigurationFromAppSettings()
                       .GetCurrentClassLogger();

See also NLog configuration with appsettings.json

Example with LoadConfigurationFromSection

Loads NLog config from Microsoft Configuration Section, and requires NLog.Extensions.Logging:

var config = new ConfigurationBuilder()
                .SetBasePath(basePath ?? Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{environment}.json", optional: true)
                .AddEnvironmentVariables().Build();
var logger = LogManager.Setup()
                       .LoadConfigurationFromSection(config)
                       .GetCurrentClassLogger();

See also NLog configuration with appsettings.json

Example with LoadConfigurationFromFile

Ensure NLog config has been loaded, and fail with exception when not:

NLog.LogManager.Setup().LoadConfigurationFromFile(optional: false);

Example with LoadConfigurationFromXml

Load NLog config from custom location (like assembly resource):

var fileXmlContent = File.ReadAllText(xmlFilePath);
NLog.LogManager.Setup().LoadConfigurationFromXml(fileXmlContent);

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

Home

  • Getting started
    • NLog Introduction
    • Example - ASP.NET Core
    • Example - .NET Core Console
  • How to use structured logging
  • Troubleshooting
    • Internal Log
  • FAQ
  • Articles about NLog

Configuration

  • All targets, layouts and layout renderers
    Popular:
    • File-target
    • ColoredConsole-target
    • Database-target
    • Mail-target
  • Using NLog with NLog.config
  • Using NLog with appsettings.json

Programmatic Configuration

  • Configure from code
  • Sandcastle documentation

Advanced

  • Add LogEvent Context details
  • Filtering log messages
  • Optimize Logging Performance
  • NLog properties with Microsoft Extension Logging
  • NLog GetCurrentClassLogger and Microsoft ILogger
  • Using Time Sources
  • Installing targets
  • Visual Studio support
  • Who is using NLog
  • Advanced Examples

Extending NLog

  • Write custom extensions
  • How to write a custom target
  • How to write a custom layout renderer
  • Writing custom conditions
  • Properties constraints for custom extensions
  • Register your custom component

Clone this wiki locally

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.