C#项目使用log4net记录日志

准备工作:

1)获取log4net.dll,http://logging.apache.org/log4net/download_log4net.cgi官网上下载源代码log4net-2.0.8-src.zip

2)用VS打开最新的sln文件,编译出log4net.dll

3)在项目工程bin\Debug中添加log4net.dll

4)工程中添加对该dll的引用(右键工程->Add->Reference),选择dll的路径

5)在写log的类中或AssemblyInfo.cs中添加 [assembly: log4net.Config.XmlConfigurator(Watch = true)]

6)解决问题Could not find schema information for the attribute 'name'

  1. In Visual Studio, open your app.config or web.config file.
  2. Go to the "XML" menu and select "Create Schema". This action should create a new file called "app.xsd" or "web.xsd".
  3. Save that file to your disk.
  4. Go back to your app.config or web.config and in the edit window, right click and select properties. From there, make sure the xsd you just generated is referenced in the Schemas property. If it's not there then add it

7)修改配置文件App.config,例:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
 
  <log4net>
    <root>
      <level value="WARN" />
      <appender-ref ref="LogFileAppender" />
      <appender-ref ref="ConsoleAppender" />
    </root>
 
    <logger name="testApp.Logging">
      <level value="DEBUG"/>
    </logger>
 
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender" >
      <param name="File" value="log-file.txt" />
      <param name="AppendToFile" value="true" />
 
      <layout type="log4net.Layout.PatternLayout">
        <param name="Header" value="[Header] "/>
        <param name="Footer" value="[Footer] "/>
        <param name="ConversionPattern" value="%d [%t] %-5p %c [%x]  - %m%n" />
      </layout>
 
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="DEBUG" />
        <param name="LevelMax" value="WARN" />
      </filter>
    </appender>
 
    <appender name="ConsoleAppender"  type="log4net.Appender.ConsoleAppender" >
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern"  value="%d [%t] %-5p %c [%x] - %m%n" />
      </layout>
    </appender>
 
  </log4net>
</configuration>

8)使用API记录log

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using log4net.Config;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

class demo
{
    private static ILog testLogger ;

    private TBoxLogRecord()
    {
        testLogger = LogManager.GetLogger("testApp.Logging");
 
    }

    static void Main(string[] args)
    {
        log.Info(DateTime.Now.ToString() + ": login success");
    }
}

这样就将信息同时输出到控制台和写入到文件名“log-file.txt”的文件中。

猜你喜欢

转载自blog.csdn.net/zheng_guan/article/details/86288789