How to set a default target in NLog

I am trying to convert an existing logging library used by a bunch of applications to use NLog. The existing logging code has no indirectness; call logging occurs directly from the caller to the webservice call. The existing registration code is implemented as a static singleton. I need to do this so that existing applications using this library do not need to change the configuration or code when they build the modified logging library. Later, I can start updating applications as needed, setting up a new logging goal, or changing the code to directly log into NLog.

To do this, I was going to make a static registration code through NLog. Existing log calls will be routed through NLog, and the existing webservice call will be wrapped in the custom target NLog.

To do this work on legacy applications without changing them, I need to programmatically configure the user target as the default (when none of them are configured in the configuration file). I would like to do this without making configuration changes to numerous existing applications, so I need to do this programmatically.

The problem is that it does not work. Any thoughts on this approach? Below is the code I tried to add in order to connect an existing log class to create a default target.

I would also not want to go to log4net. Just looking at the API, I chose NLog initially, as the names made more sense to me.

public static class LegacyLogger
{
    static LegacyLogger()
    {
        if (LogManager.Configuration == null
            || LogManager.Configuration.GetConfiguredNamedTargets().Count == 0)
        {
            if (LogManager.Configuration == null)
            {
                LogManager.Configuration = new LoggingConfiguration();
            }

            //LogManager.Configuration.AddTarget("LegacyLogger", new NLog.Targets.DebuggerTarget());
            LogManager.Configuration.AddTarget("LegacyLogger", new LegacyLoggerTarget());
        }

        _logger = LogManager.GetCurrentClassLogger();
    }
+3
source share
1 answer

Well, if you are new to NLog since I was, check out the examples installed with the installer cover about everything. In this case, I need:

public static class LegacyLogger
{
    static LegacyLogger()
    {
        if (LogManager.Configuration == null
            || LogManager.Configuration.GetConfiguredNamedTargets().Count == 0)
        {
            NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(new LegacyLoggerTarget(), LogLevel.Trace);
        }

        _logger = LogManager.GetCurrentClassLogger();
    }
+4
source

Source: https://habr.com/ru/post/1761635/


All Articles