Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Target does not update on LogManager.ReconfigExistingLoggers(); #39

Open
bobcat1506 opened this issue Jun 19, 2020 · 1 comment
Open

Comments

@bobcat1506
Copy link

We store our connection strings and credentials outside of our app in a secrets vault, but we like to keep the rest of our config in config files. We marry the two just before starting up the app. The following code works great with other targets such as the DatabaseTarget, but doesn't work with MongoTarget.

    static void Main(string[] args)
    {
        Logger logger = NLog.LogManager.GetCurrentClassLogger();

        // do startup activities like building the host and log to files
        try
        {
            // build host
        }
        catch (Exception ex)
        {
            // logger.LogException()
            // the logger never writes anything to mongo and never throws an error
        }

        // set connection string after retrieving username/password from secrets store
        var mongo = LogManager.Configuration.FindTargetByName("mongoCustom") as MongoTarget;
        mongo.ConnectionString = "mongodb://localhost/Logging";
        LogManager.ReconfigExistingLoggers();

        // run the host
        try
        {
            // host.Run()
        }
        catch (Exception ex)
        {
            // logger.LogException()
        }
    }

<target xsi:type="Mongo" name="mongoCustom" includeDefaults="false" collectionName="CustomLog" cappedCollectionSize="26214400">

@snakefoot
Copy link
Contributor

Think it will work if you just provide a "dummy"-value for connectionString like this:

<target xsi:type="Mongo" name="mongoCustom" includeDefaults="false" collectionName="CustomLog" cappedCollectionSize="26214400" connectionString="NotReadyYet">

When Mongo-Target initializes then it validates if connnectionString contains an non-empty value. If the value is empty then the Mongo-Target throws an exception, and the Mongo-Target goes into disabled state (Stays disabled even after having updated ConnectionString-property).

Alternative solution is doing this:

mongo.ConnectionString = "mongodb://localhost/Logging";
LogManager.Configuration = LogManager.Configuration; // Close all targets and initialize them again

But it can have side-effects, and might not work with all custom NLog-targets

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants