我一直在使用log4net,但有一件事我一直没有弄清楚,那就是如何判断内部发生了什么。例如,我在我的项目中有一个控制台appender和一个数据库appender。我对数据库和代码做了一些更改,现在数据库追加器不再工作了。我最终会找出原因,但如果我能看到log4net内部发生了什么,将会有很大帮助。

log4net是否生成了任何类型的输出,以便我可以查看以确定问题的根源?


首先,你必须在应用程序配置文件上设置这个值:

<configuration>
   <appSettings>
      <add key="log4net.Internal.Debug" value="true"/>
   </appSettings>
</configuration>

然后,为了确定你想要保存输出的文件,你可以在同一个.config文件中添加以下代码:

<configuration>
...

<system.diagnostics>
    <trace autoflush="true">
        <listeners>
            <add 
                name="textWriterTraceListener" 
                type="System.Diagnostics.TextWriterTraceListener" 
                initializeData="C:\tmp\log4net.txt" />
        </listeners>
    </trace>
</system.diagnostics>

...
</configuration>

你可以在下面找到更详细的解释 “如何启用log4net内部调试?” 在log4net常见问题解答页面。


除了上面的答案之外,您还可以使用这一行来实时查看日志,而不是使用c:\tmp\log4net.txt输出。

log4net.Util.LogLog.InternalDebugging = true;

例如,在一个控制台应用程序中,你可以添加这个,然后实时观察输出。它很适合在一个小型测试工具中调试log4net,以查看正在测试的appender发生了什么。


如果你使用的是log4net配置文件,你也可以通过更改顶部节点来打开调试:

<log4net debug="true">

这将在重新加载配置并假设跟踪侦听器已正确设置之后起作用。


如果内部日志没有提供足够的信息,那么构建和调试源代码就非常容易。如果您不想将此与您的开发项目混淆,可以添加一个简单的控制台应用程序,它只记录消息,复制项目的log4net。配置到此应用程序,并调试相关的类。


确保您的入口点所在的根应用程序将某些内容记录到log4net。给它一个这样的例子:

private static ILog logger = LogManager.GetLogger(typeof(Program));
static void Main(string[] args)
{
    logger.InfoFormat("{0} v.{1} started.", Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString());

With 2.0.8, I had an interesting situation. I created a library project and a test exe project that would demo it's capabilities. The library project was set up to use Log4net as was the exe project. The exe project used the assemblyinfo attribute to register the config, yet I was getting no logging output to either the console or the log file. When I turned on log4net internal debug logging, I got some internal messages written to the console, but still none of my normal logs. No errors were being reported. It all started working when I added the above code to my program. Log4net was otherwise setup correctly.


在log4net 2.0.8中,似乎不可能在单独的DLL中使用log4net进行日志记录。如果我尝试这样做,结果非常奇怪:不再执行日志记录。使用debug选项初始化log4net时没有显示错误。

就像K0D4说的,你应该在你的主模块中有一个对log4net的引用,它应该在程序开始时调用一次,一切都很好。

在log4net的下一个版本中,这个错误可能会被修复。