Enterprise Library Fluent API и файлы журналов, которые не обновляются

Я использую Fluent API для обработки различных параметров конфигурации для ведения журнала с использованием EntLib.

Я создаю раздел loggingConfiguration вручную в коде. Кажется, он отлично работает, за исключением того, что RollingFlatFileTraceListener на самом деле не сворачивает файл. Он будет соблюдать ограничение по размеру и ограничивать объем данных, которые он записывает в файл, но на самом деле он не создает новый файл и не продолжает журналы.

Я протестировал его с образцом приложения и app.config, и, похоже, он работает. Так что я предполагаю, что я что-то упускаю, хотя все параметры конфигурации, которые кажутся нужными, есть.

Вот основы кода (с жестко закодированными значениями, чтобы показать конфигурацию, которая, похоже, не работает): //Создайте построитель конфигурации для Fluent API var configBuilder = new ConfigurationSourceBuilder();

            //Start building the logging config section                 
            var logginConfigurationSection = new LoggingSettings("loggingConfiguration", true, "General");                 
            logginConfigurationSection.RevertImpersonation = false;
            var _rollingFileListener = new RollingFlatFileTraceListenerData("Rolling Flat File Trace Listener", "C:\\tracelog.log", "----------------------", "",
                            10, "MM/dd/yyyy", RollFileExistsBehavior.Increment,
                            RollInterval.Day, TraceOptions.None,
                            "Text Formatter", SourceLevels.All);


            _rollingFileListener.MaxArchivedFiles = 2;

            //Add trace listener to current config
            logginConfigurationSection.TraceListeners.Add(_rollingFileListener);

            //Configure the category source section of config for flat file
            var _rollingFileCategorySource = new TraceSourceData("General", SourceLevels.All);

            //Must be named exactly the same as the flat file trace listener above.
            _rollingFileCategorySource.TraceListeners.Add(new TraceListenerReferenceData("Rolling Flat File Trace Listener"));

            //Add category source information to current config
            logginConfigurationSection.TraceSources.Add(_rollingFileCategorySource);          

            //Add the loggingConfiguration section to the config.
            configBuilder.AddSection("loggingConfiguration", logginConfigurationSection);

            //Required code to update the EntLib Configuration with settings set above.
            var configSource = new DictionaryConfigurationSource();
            configBuilder.UpdateConfigurationWithReplace(configSource);

            //Set the Enterprise Library Container for the inner workings of EntLib to use when logging
            EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);

Любая помощь будет оценена по достоинству!


person mainedev    schedule 30.06.2011    source источник


Ответы (1)


Ваш шаблон метки времени неверен. Это должно быть ггг-мм-дд вместо ММ/дд/гггг. Символ ‘/’ не поддерживается.

Кроме того, вы можете достичь своей цели, используя fluent интерфейс конфигурации намного проще. Вот как:

    ConfigurationSourceBuilder formatBuilder = new ConfigurationSourceBuilder();

    ConfigurationSourceBuilder builder = new ConfigurationSourceBuilder();
    builder.ConfigureLogging().LogToCategoryNamed("General").
        SendTo.
        RollingFile("Rolling Flat File Trace Listener")
        .CleanUpArchivedFilesWhenMoreThan(2).WhenRollFileExists(RollFileExistsBehavior.Increment)
        .WithTraceOptions(TraceOptions.None)
        .RollEvery(RollInterval.Minute)
        .RollAfterSize(10)
        .UseTimeStampPattern("yyyy-MM-dd")
        .ToFile("C:\\logs\\Trace.log")
        .FormatWith(new FormatterBuilder().TextFormatterNamed("textFormatter"));

    var configSource = new DictionaryConfigurationSource(); 
    builder.UpdateConfigurationWithReplace(configSource); 
    EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
    var writer = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();

    DateTime stopWritingTime = DateTime.Now.AddMinutes(10);
    while (DateTime.Now < stopWritingTime)
    {
        writer.Write("test", "General");
    }
person Grigori Melnik    schedule 26.08.2011