Cannot load nlog.config in Xamarin

心不动则不痛 提交于 2019-12-11 15:27:15

问题


I cannot read nlog.config file in asset folder of android platform

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

How to read nlog file and also this file is in android asset.


回答1:


You can also make use of Xamarin resource. Put the NLog.config file into the library 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);
}

See also: https://github.com/NLog/NLog/wiki/Explicit-NLog-configuration-loading#loading-nlog-configuration-from-xamarin-resource




回答2:


you could also try to use this (nlog.config file with a Build Action as an AndroidAsset):

NLog.LogManager.Configuration = new XmlLoggingConfiguration (XmlTextReader.Create(Assets.Open ("NLog.config")), null);

refer to: https://github.com/NLog/NLog/blob/master/src/NLog/Config/LoggingConfigurationFileLoader.cs#L101-L120




回答3:


You can add an extension method to your context class that gets you the required asset as a stream:

 public static class Utils
 {
   public static Stream GetFromAssets(this Context context, string assetName)
    {
        AssetManager assetManager = context.Assets;
        Stream inputStream;
        try
        {
            using (inputStream = assetManager.Open(assetName))
            {
                return inputStream;
            }

        }
        catch (Exception e)
        {
            return null;
        }
    }
 }

And then in your activity context access it like:

var Asset= context.GetFromAssets("AssetName");

Note that this will return a System.IO.Stream.

Good luck

Revert in case of queries.




回答4:


For Xamarin Android "NLog.config" (in this casing) in the assets folder will be loaded automatically. If the file name is different, then use:

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



回答5:


Thanks for your response. I resolved this issue by setting autoReload="false" throwExceptions="false". Due to these two my config file was not visible. I dont know how they affect the file visibility but setting above two to false i can get config file now Thanks,



来源:https://stackoverflow.com/questions/55488453/cannot-load-nlog-config-in-xamarin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!