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

HI там,

Я просто настроил часть блока приложения журналирования 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 \ nОс исключение: InvalidOperationException - Тип LogWriter не может быть создан.Вы должны настроить контейнер для предоставления этого значения. \ R \ n ----------------------------------------------- \ r \ nВ момент исключения контейнер был: \ r \ n \ r \ n Решение Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter, (нет) \ 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 Ответ

3 голосов
/ 02 апреля 2011

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

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

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

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

...