将日志写入文件

时间:2012-03-21 13:09:17

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

将日志从log4net写入文件时遇到了一些麻烦。我似乎按照手册中的描述完成所有操作,但这不起作用。这是我的logging.config文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="log.txt" />
      <appendToFile value="true" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %message%newline" />
      </layout>
    </appender>
  </log4net>
</configuration>

请帮助一个实际有效的配置文件示例。

5 个答案:

答案 0 :(得分:77)

以下是在Visual Studio 2012和.NET 4.5下将Log4Net添加到项目的完整分步指南。

  1. 在您的解决方案中添加新的C#控制台应用程序。

  2. 选择Tools >> Library Package Manager >> Manage NuGet Packages For Solution并搜索log4net。安装它,并选择要添加log4net引用的项目。 enter image description here

  3. 修改Program.cs

  4. using System;
    namespace Log4Net
    {    
        class Program
        {
            private static readonly log4net.ILog log = log4net.LogManager.GetLogger
                    (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            static void Main(string[] args)
            {
                Console.WriteLine("Writing to \"log.txt\" in the same directory as the .exe file.\n");
                log.Info("Info logging");
                try
                {
                    throw new Exception("Exception!");
                }
                catch (Exception e)
                {
                    log.Error("This is my error", e);
                }
                Console.WriteLine("[any key to exit]");
                Console.ReadKey();
                }
            }
        }
    }
    
    1. 添加log4.config,右键点击并选择Properties,然后选择Copy to Output Directory - Copy If Newer
    2. <?xml version="1.0" encoding="utf-8" ?>
      <configuration>
        <configSections>
          <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
        </configSections>
      
        <log4net>
          <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
            <file value="log.txt" />
            <appendToFile value="true" />
            <rollingStyle value="Size" />
            <maxSizeRollBackups value="10" />
            <maximumFileSize value="250KB" />
            <staticLogFileName value="true" />
            <layout type="log4net.Layout.PatternLayout">
              <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
            </layout>
          </appender>
          <root>
            <level value="ALL" />
            <appender-ref ref="RollingFileAppender" />
          </root>
        </log4net>
      </configuration>
      
      1. 修改App.Config,使其符合以下条件:
      2. <?xml version="1.0" encoding="utf-8" ?>
        <configuration>
            <startup> 
                <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
            </startup>
            <appSettings>
                <add key="log4net.Config" value="log4.config"/>
                <add key="log4net.Config.Watch" value="True"/>
                <add key="log4net.Internal.Debug" value="False"/>
            </appSettings>
        </configuration>
        
        1. 运行程序并观察在输出log.txt目录中创建的文件\bin\Debug\

          2013-08-10 11:54:26,798 [10] INFO  Log4Net.Program [(null)] - Info logging
          2013-08-10 11:54:26,824 [10] ERROR Log4Net.Program [(null)] - This is my error
          System.Exception: Exception!
             at Log4Net.Program.Main(String[] args) in C:\Test\Log4Net\Program.cs:line 14
          
        2. 将来,如果您想将log4net添加到其他项目,请选择Tools >> Library Package Manager >> Manage NuGet Packages For Solution选择log4net,然后点击Manage,然后勾选您想要的项目将log4net添加到。 enter image description here

答案 1 :(得分:41)

您似乎没有引用您的appender的<root>元素:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

    <log4net>
      <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <file value="log.txt" />
        <appendToFile value="true" />
        <rollingStyle value="Size" />
        <maxSizeRollBackups value="10" />
        <maximumFileSize value="250KB" />
        <staticLogFileName value="true" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
        </layout>
      </appender>
      <root>
        <level value="INFO" />
        <appender-ref ref="RollingFileAppender" />
      </root>
    </log4net>
</configuration>

答案 2 :(得分:18)

首次启动应用程序时是否调用了configure方法?

log4net.Config.XmlConfigurator.Configure();

如果是的话。你应该好。检查您正在编写的磁盘上的文件权限。

如果您需要,还可以启用log4net内部调试,以找出问题所在。

http://logging.apache.org/log4net/release/faq.html#troubleshooting

答案 3 :(得分:6)

您可以做两件事:

其一,如果你想使用一个单独的配置文件,通过在app.config文件中添加以下内容,它将自动配置日志记录。

<?xml version="1.0"?>
<configuration>
    <appSettings>
        <add key="log4net.Config" value="log4.config"/>
        <add key="log4net.Config.Watch" value="True"/>
        <add key="log4net.Internal.Debug" value="False"/>
    </appSettings>
</configuration>

否则,您需要在应用程序的开头启动日志记录。

//Initiate logging based on web.config file
log4net.Config.XmlConfigurator.Configure();

// Create a logger for use in this class
log4net.ILog log4 = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

答案 4 :(得分:3)

优秀。答案是正确的......除了他们没有为我工作

搜索网并最终发现我在Assembly.cs中缺少以下行:

$ cat data.txt
  a:23 b:25 c:76 d:45
  a:21 b:24 c:25 
  a:20 d:52 e:75 f:75 g:52
  ...
  (many lines)
  ...