Home > Mobile >  NLog how to use Isolated LogFactories with a custom logger class
NLog how to use Isolated LogFactories with a custom logger class

Time:11-24

I ran into a issue because LogManager is global, so my two projects were overriding each other's logging config. NLog log calls in the first project would work fine, but then when calling into the second project, all future log calls would be logged with the second projects config.

Example:

  • Target 1 "First log in first project" (supposed to be target 1)
  • Target 2 "Second log in second project" (supposed to be target 2)
  • Target 2 "Third log in first project" (supposed to be target 1)

I found Isolated logfactory which solved my issue, now the loggers has the correct config. However I cannot figure out how to use my custom NLog class with this method of making LogFactories.

This works great (but doesn't let me use my custom class with methods):

private static Logger logger = MyLogger.MyLogManager.Instance.GetCurrentClassLogger();

This:

private static MyLogger logger = (MyLogger)MyLogger.MyLogManager.Instance.GetCurrentClassLogger();

Throws:

System.TypeInitializationException: 'The type initializer for 'MyProject.MyClass.MyMethod' threw an exception.'
InvalidCastException: Unable to cast object of type 'NLog.Logger' to type 'MyProject.NLogConfigFolder.MyLogger'.

I have tried to cast Logger to MyLogger but have not been able to do so successfully.

Here is my setup for the isolated LogFactory:

public class MyLogger : Logger
  {
    public class MyLogManager
    {
      public static LogFactory Instance { get { return _instance.Value; } }
      private static Lazy<LogFactory> _instance = new Lazy<LogFactory>(BuildLogFactory);

      private static LogFactory BuildLogFactory()
      {
        string configFilePath = "path/to/my/config"

        LogFactory logFactory = new LogFactory();
        logFactory.Configuration = new XmlLoggingConfiguration(configFilePath, true, logFactory);
        return logFactory;
      }
    }
    // Other methods here
  }

Thank you for your time and help with this problem.

CodePudding user response:

Think you just need to change:

(MyLogger)MyLogger.MyLogManager.Instance.GetCurrentClassLogger()

Into this:

MyLogger.MyLogManager.Instance.GetCurrentClassLogger<MyLogger>()

See also: https://nlog-project.org/documentation/v5.0.0/html/Overload_NLog_LogFactory_GetCurrentClassLogger.htm

  • Related