C# 将日志写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9805281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:57:23  来源:igfitidea点击:

Writing logs to file

c#.netlogginglog4netlog4net-configuration

提问by Yury Pogrebnyak

I have some troubles while writing logs from log4net to the file. I seem to do all as described in manual, but that does not work. Here is my logging.config file:

我在将日志从 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>

Please help with an example of configuration file which actually works.

请帮助提供实际工作的配置文件示例。

采纳答案by jlew

You don't seem to have a <root>element that references your appender:

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

<?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>

回答by Shyju

Did you call the configure method when the application starts for the first time ?

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

log4net.Config.XmlConfigurator.Configure();

If yes. You should be good. Check the file permissions on the disk you are writing.

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

If you want you can enable log4net internal debugging also to figure out what is wrong.

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

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

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

回答by Kevin Green

There are two things that you can do:

您可以做两件事:

One, if you want to use a seperate config file, by adding the following to you app.config file it will configure logging automatically.

一,如果您想使用单独的配置文件,通过将以下内容添加到您的 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>

Otherwise, you need to initiate logging in the start of your application.

否则,您需要在应用程序启动时启动登录。

//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);

回答by Contango

Here is a complete step-by-step guide to adding Log4Net to your project, under Visual Studio 2012 and .NET 4.5.

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

  1. Add a new C# console app to your solution.

  2. Select Tools >> Library Package Manager >> Manage NuGet Packages For Solutionand search for log4net. Install it, and select which project(s) you want to add the log4net references. enter image description here

  3. Edit Program.cs:

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

  2. 选择Tools >> Library Package Manager >> Manage NuGet Packages For Solution并搜索log4net。安装它,然后选择要添加 log4net 引用的项目。 在此处输入图片说明

  3. 编辑Program.cs

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. Add log4.config, right click and select Propertiesthen select Copy to Output Directory - Copy If Newer.
  1. 添加log4.config,右键单击并选择Properties然后选择Copy to Output Directory - Copy If Newer
<?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. Edit App.Configso it matches the following:
  1. 编辑App.Config使其与以下内容匹配:
<?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. Run the program and observe the file log.txtthat is created in the output \bin\Debug\directory:

    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. In the future, if you want to add log4netto another Project, select Tools >> Library Package Manager >> Manage NuGet Packages For Solutionselect log4netand click Managethen tick the Projects you want to add log4netto. enter image description here

  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到的项目。 在此处输入图片说明

回答by JAnton

Fantastic. The answers are correct... except that they weren't working for me

极好的。答案是正确的......除了它们不适合我

Searched the net and finally discovered I was missing the following line in Assembly.cs:

搜索网络,终于发现我在Assembly.cs中缺少以下行:

[assembly: log4net.Config.XmlConfigurator]