EntLib5: блок приложения Loggin не регистрируется в журнале событий (исключение: тип LogWriter не может быть создан) - Может ли кто-нибудь помочь?

Всем привет,

Я просто настроил часть блока приложения ведения журнала в Enterprise Library 5. Я думаю, что все сделал правильно, но он не регистрирует в журнале событий ошибки метода записи и дает мне следующее исключение.

    The type LogWriter cannot be constructed. 
         You must configure the container to supply this value.

Может ли кто-нибудь проверить меня или сказать, что мне не хватает ..

Прежде всего, я работаю в Windows 7 с приложением winforms.

Вот мой метод, который создает журнал, и вы видите метод записи.

public class Logger : ILogger
{
    public void SendTest(string test)
    {
        LogEntry log = new LogEntry();
        log.EventId = 300;
        log.Message = test;
        log.Categories.Add("testing");
        log.Severity = TraceEventType.Information;
        log.Priority = 5;
        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(log);

    }
}

Все мои конфиги были собраны с помощью редактора entlib5, а не вручную. И подтвердил это, путь, по которому entlib.config находится

    filePath="C:\myapp\entlib.config" />

Вот мой app.config, который УКАЗЫВАЕТ на мой entlib.config

<?xml version="1.0"?>
<configuration>
<configSections>
    <section name="enterpriseLibrary.ConfigurationSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<enterpriseLibrary.ConfigurationSource selectedSource="System Configuration Source">
    <sources>
        <add name="System Configuration Source" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.SystemConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        <add name="File-based Configuration Source" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            filePath="C:\myapp\entlib.config" />
    </sources>
    <redirectSections>
        <add sourceName="File-based Configuration Source" name="Redirected Section" />
    </redirectSections>
</enterpriseLibrary.ConfigurationSource>
<startup><supportedRuntime version="v2.0.50727"/></startup></configuration>

и вот мой entlib.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    </configSections>
    <loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
        <listeners>
            <add name="Event Log Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                source="Enterprise Library Logging" formatter="Text Formatter"
                log="" machineName="." traceOutputOptions="None" />
        </listeners>
        <formatters>
            <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                template="Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}"
                name="Text Formatter" />
        </formatters>
        <categorySources>
            <add switchValue="All" name="General">
                <listeners>
                    <add name="Event Log Listener" />
                </listeners>
            </add>
        </categorySources>
        <specialSources>
            <allEvents switchValue="All" name="All Events" />
            <notProcessed switchValue="All" name="Unprocessed Category" />
            <errors switchValue="All" name="Logging Errors &amp; Warnings">
                <listeners>
                    <add name="Event Log Listener" />
                </listeners>
            </errors>
        </specialSources>
    </loggingConfiguration>
</configuration>

ИЗМЕНИТЬ Вопрос был обновлен новым app.config, чтобы включить

<redirectSections>
    <add sourceName="File-based Configuration Source" name="Redirected Section" />
</redirectSections>

Я все еще получаю сообщение об ошибке.

 Activation error occured while trying to get instance of type

LogWriter, ключ ""

и внутреннее исключение

Ошибка разрешения зависимости, type = \ "Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter \", name = \ "(none) \". \ R \ nИсключение произошло во время: при разрешении. \ R \ nException is: InvalidOperationException - Тип LogWriter не может быть сконструирован. Вы должны настроить контейнер для предоставления этого значения. \ R \ n ------------------------------------ ----------- \ r \ nВ момент исключения контейнер был: \ r \ n \ r \ n Разрешение Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter, (none) \ r \ n "}

Я использовал конфигуратор EntLib для создания обоих файлов.

В entlib.config я принял значение по умолчанию, поскольку, похоже, в него включен прослушиватель EventLog.

ИЗМЕНИТЬ

это моя строка в файле entlib.config, журнал пуст - эмм, это правильно?

    <add name="Event Log Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        source="Enterprise Library Logging" formatter="Text Formatter"
        log="" machineName="." traceOutputOptions="None" />

ИЗМЕНИТЬ

МОЙ Logger.write находится в dll, но мой app.config / entlib.config находится в приложении winforms .. приложение winforms имеет ссылку на проект dll, в котором я пишу журнал.

И dll, и winforms имеют ссылку на

   Microsoft.Practices.EnterpriseLibrary.Logging

а также используя единицу, имеет

   Microsoft.Practices.Unity

   Microsoft.Practices.Unity.Interception



Ответы (1)


Мартин, вы создали файловый источник конфигурации, но не перенаправили на него раздел ведения журнала.

Добавьте следующее в App.config внутри узла enterpriseLibrary.ConfigurationSource:

<redirectSections>
      <add sourceName="File-based Configuration Source" name="loggingConfiguration" />
</redirectSections>

Кроме того, я рекомендую лабораторию по источникам конфигурации из Набор практических занятий для Enterprise Library 5.0. Он охватывает этот и более сложные сценарии.

person Grigori Melnik    schedule 02.04.2011
comment
Спасибо, Григорий, да, у меня этого не было, я обновил его ... Я обновлю свой вопрос ... Это все еще ошибка. Любые идеи? - person Martin; 03.04.2011