-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Explicit NLog configuration loading
ℹ️ See also Environment specific NLog Logging Configuration
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");
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);
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);
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);
- Troubleshooting Guide - See available NLog Targets and Layouts: https://nlog-project.org/config
- Getting started
- How to use structured logging
- Troubleshooting
- FAQ
- Articles about NLog
-
All targets, layouts and layout renderers
Popular: - Using NLog with NLog.config
- Using NLog with appsettings.json