- Notifications
You must be signed in to change notification settings - Fork1.4k
Explicit NLog configuration loading
ℹ️ See alsoEnvironment specific NLog Logging Configuration
NLog will automaticallyscan for configuration files, but sometimes the platform requires explicit configuration loading like this:
NLog.LogManager.Configuration=newNLog.Config.XmlLoggingConfiguration("nlog.config");
The configuration can also come from standard string like this:
varxmlStream=newSystem.IO.StringReader(xmlString);varxmlReader=System.Xml.XmlReader.Create(xmlStream);NLog.LogManager.Configuration=newNLog.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 thebuild action toembedded resource.
publicstaticStreamGetEmbeddedResourceStream(Assemblyassembly,stringresourceFileName){varresourcePaths=assembly.GetManifestResourceNames().Where(x=>x.EndsWith(resourceFileName,StringComparison.OrdinalIgnoreCase)).ToList();if(resourcePaths.Count==1){returnassembly.GetManifestResourceStream(resourcePaths.Single());}returnnull;}varnlogConfigFile=GetEmbeddedResourceStream(myAssembly,"NLog.config");if(nlogConfigFile!=null){varxmlReader=System.Xml.XmlReader.Create(nlogConfigFile);NLog.LogManager.Configuration=newXmlLoggingConfiguration(xmlReader,null);}
NLog v5 introduces thisfluent configuration extension-method:
NLog.LogManager.Setup().LoadConfigurationFromAssemblyResource(typeof(App).GetTypeInfo().Assembly);
assets folder forNLog.config. Instead consider using Embedded Assembly Resource
With NLog v4 then the NLog.dll built for Xamarin Android would automatically scan theassets folder forNLog.config.
If the file name is different, then NLog v4 also supported this:
LogManager.Configuration=newXmlLoggingConfiguration("assets/someothername.config");
If using the NLog.dll built for NetStandard in Xamarin, then the Androidassets-folder is not recognized or scanned. Instead consider using Assembly Resource.
To explicly read file fromAndroid Assets, then one can do this:
AssetManagerassets=this.Assets;varassetStream=assets.Open("NLog.config");varxmlReader=System.Xml.XmlReader.Create(assetStream);NLog.LogManager.Configuration=newXmlLoggingConfiguration(xmlReader,null);
-Troubleshooting Guide - See available NLog Targets and Layouts:https://nlog-project.org/config
- All targets, layouts and layout renderers
Popular: - Using NLog with NLog.config
- Using NLog with appsettings.json