1

我正在动态创建企业日志记录设置。

保存配置后,我添加了ConfigurationManager.RefreshSection("loggingConfiguration")刷新app.config我的 Windows 服务。但是日志没有创建前几秒(10 秒)。我丢失了一些需要记录的数据。

下面是我编写的以编程方式创建日志设置的代码。

    public static void CreateLoggingSettings(string configpath, string logCategory, string logfilePath)
    {
        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
        TextFormatterData txtformat;
        FlatFileTraceListenerData tldata;
        LogSource ls;
        TraceSourceData tsd;
        TraceListenerReferenceData tlr;
        try
        {

            fileMap.ExeConfigFilename = configpath;
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            LoggingSettings loggingSettings = config.GetSection(LoggingSettings.SectionName) as LoggingSettings;

            if (loggingSettings == null ||
                (loggingSettings.Formatters.Contains(logCategory) &&
                 loggingSettings.TraceListeners.Contains(logCategory))) return;

            txtformat = new TextFormatterData(logCategory, "{timestamp(local)}{tab}{message}");
            loggingSettings.Formatters.Add(txtformat);

            tldata = new FlatFileTraceListenerData(logCategory, logfilePath + logCategory + ".log",
                txtformat.Name);
            loggingSettings.TraceListeners.Add(tldata);

            ls = new LogSource(tldata.Name, System.Diagnostics.SourceLevels.All);
            tsd = new TraceSourceData(ls.Name, System.Diagnostics.SourceLevels.All);
            tlr = new TraceListenerReferenceData(tldata.Name);
            tsd.TraceListeners.Add(tlr);

            loggingSettings.TraceSources.Add(tsd);
            config.Save(ConfigurationSaveMode.Full);
            ConfigurationManager.RefreshSection("loggingConfiguration");

        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            fileMap = null;
            txtformat = null;
            tldata = null;
            ls = null;
            tsd = null;
            tlr = null;
        }
    }
}

但它工作正常。当我调试服务时。有任何想法吗?

4

0 回答 0