コード例 #1
0
        internal void ReloadConfigOnTimer(object state)
        {
            if (_reloadTimer == null && _isDisposing)
            {
                return; //timer was disposed already.
            }

            LoggingConfiguration oldConfig = (LoggingConfiguration)state;

            InternalLogger.Info("Reloading configuration...");
            lock (_lockObject)
            {
                if (_isDisposing)
                {
                    return; //timer was disposed already.
                }

                var currentTimer = _reloadTimer;
                if (currentTimer != null)
                {
                    _reloadTimer = null;
                    currentTimer.WaitForDispose(TimeSpan.Zero);
                }
            }

            lock (_logFactory._syncRoot)
            {
                LoggingConfiguration newConfig;
                try
                {
                    if (!ReferenceEquals(_logFactory._config, oldConfig))
                    {
                        InternalLogger.Warn("NLog Config changed in between. Not reloading.");
                        return;
                    }

                    newConfig = oldConfig.ReloadNewConfig();
                    if (newConfig == null || ReferenceEquals(newConfig, oldConfig))
                    {
                        return;
                    }
                }
                catch (Exception exception)
                {
                    if (exception.MustBeRethrownImmediately())
                    {
                        throw;  // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
                    }

                    InternalLogger.Warn(exception, "NLog configuration failed to reload");
                    _logFactory?.NotifyConfigurationReloaded(new LoggingConfigurationReloadedEventArgs(false, exception));
                    return;
                }

                try
                {
                    TryUnwatchConfigFile();

                    _logFactory.Configuration = newConfig;  // Triggers LogFactory to call Activated(...) that adds file-watch again

                    _logFactory?.NotifyConfigurationReloaded(new LoggingConfigurationReloadedEventArgs(true));
                }
                catch (Exception exception)
                {
                    if (exception.MustBeRethrownImmediately())
                    {
                        throw;  // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
                    }

                    InternalLogger.Warn(exception, "NLog configuration reloaded, failed to be assigned");
                    _watcher.Watch(oldConfig.FileNamesToWatch);
                    _logFactory?.NotifyConfigurationReloaded(new LoggingConfigurationReloadedEventArgs(false, exception));
                }
            }
        }