尝试在C#中获取log4net日志文件路径时出错

时间:2011-11-23 11:18:43

标签: c# .net-3.5 log4net log4net-configuration

我在尝试检索C#中的log4net日志文件路径时遇到此错误。 这是我使用的代码。

Hierarchy hierarchy = LogManager.GetRepository() as Hierarchy; // WORKS FINE
Logger logger = hierarchy.Root;                                // WORKS FINE
FileAppender appender = logger.Appenders[0] as FileAppender;   // ERROR!!! - Index was out of range. Must be non-negative and less than the size of the collection. [0] Specified argument was out of the range of valid values.
string file = appender.File;

似乎上面提到的数组中没有Appender对象。 有没有人来过这个?

我在App.config中的log4net配置部分:

<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>

<log4net debug="true">
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender,log4net" >
        <param name="File" value="C:\\SampleLog\\log.txt" />
        <param name="AppendToFile" value="true" />
        <layout type="log4net.Layout.PatternLayout,log4net">
            <param name="ConversionPattern" value="%date [%thread] %-5level %logger - %message%newline" />
        </layout>
    </appender>
    <root>
        <priority value="ALL" />
        <appender-ref ref="LogFileAppender" />
    </root>
    <category name="Sample.Form1">
        <priority value="ALL" />
    </category>
</log4net>

1 个答案:

答案 0 :(得分:3)

一种可能是您尚未加载配置。你打电话给XmlConfigurator.Configure()吗?

如果是,您是否在该呼叫之前执行了相关代码?也许就这么简单。