Корпоративная библиотека Fluent API и файлы журналов не катятся - PullRequest
1 голос
/ 30 июня 2011

Я использую 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);

Буду признателен за любую помощь!

1 Ответ

4 голосов
/ 26 августа 2011

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

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

    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");
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...