Skip to content

Explicit NLog configuration loading

Rolf Kristensen edited this page Jun 24, 2023 · 28 revisions

ℹ️ See also Environment specific NLog Logging Configuration

Loading NLog configuration from file

NLog will automatically scan for configuration files, but sometimes the platform requires explicit configuration loading like this:

NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration("nlog.config");

Loading NLog configuration from string

The configuration can also come from standard string like this:

var xmlStream = new System.IO.StringReader(xmlString);
var xmlReader = System.Xml.XmlReader.Create(xmlStream);
NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(xmlReader, null);

NLog v5 introduces this fluent extension-method:

NLog.LogManager.Setup().LoadConfigurationFromXml(xmlString);

Loading NLog config from Assembly Resource

You need to put the NLog.config file into the application-project, then edit file's properties - change the build action to embedded resource.

public static Stream GetEmbeddedResourceStream(Assembly assembly, string resourceFileName)
{
  var resourcePaths = assembly.GetManifestResourceNames()
    .Where(x => x.EndsWith(resourceFileName, StringComparison.OrdinalIgnoreCase))
    .ToList();
  if (resourcePaths.Count == 1)
  {
    return assembly.GetManifestResourceStream(resourcePaths.Single());
  }
  return null;
}

var nlogConfigFile = GetEmbeddedResourceStream(myAssembly, "NLog.config");
if (nlogConfigFile != null)
{
    var xmlReader = System.Xml.XmlReader.Create(nlogConfigFile);
    NLog.LogManager.Configuration = new XmlLoggingConfiguration(xmlReader, null);
}

NLog v5 introduces this fluent configuration extension-method:

NLog.LogManager.Setup().LoadConfigurationFromAssemblyResource(typeof(App).GetTypeInfo().Assembly);

Xamarin Android

⚠️ NLog v5 will no longer scan the assets folder for NLog.config. Instead consider using Embedded Assembly Resource

With NLog v4 then the NLog.dll built for Xamarin Android would automatically scan the assets folder for NLog.config.

If the file name is different, then NLog v4 also supported this:

LogManager.Configuration = new XmlLoggingConfiguration("assets/someothername.config");

If using the NLog.dll built for NetStandard in Xamarin, then the Android assets-folder is not recognized or scanned. Instead consider using Assembly Resource.

To explicly read file from Android Assets, then one can do this:

AssetManager assets = this.Assets;
var assetStream = assets.Open("NLog.config");
var xmlReader = System.Xml.XmlReader.Create(assetStream);
NLog.LogManager.Configuration = new XmlLoggingConfiguration(xmlReader, null);
Clone this wiki locally