C#log4net的使用

一,下载log4net.dll,在项目中添加引用

二,在站点根目录添加,配置文件(log4net.xml), <file value="logs/logfile.txt"/>配置了文件的输出路径,确认是否添加了文件夹和文件

<?xml version="1.0" encoding="utf-8" ?>
<log4net debug="false">
  <appender name="trace" type="log4net.Appender.TraceAppender, log4net">
    <layout type="log4net.Layout.PatternLayout,log4net">
      <param name="ConversionPattern" value="%d{ABSOLUTE} %c{1}(%L) %M [%-5p] - %m%n"/>
    </layout>
  </appender>
  <appender name="console" type="log4net.Appender.ConsoleAppender, log4net">
    <layout type="log4net.Layout.PatternLayout,log4net">
      <param name="ConversionPattern" value="%d{ABSOLUTE} %c{1}(%L) %M [%-5p] - %m%n"/>
    </layout>
  </appender>
  <appender name="rolling" type="log4net.Appender.RollingFileAppender, log4net">
    <!--日志文件名和输出路径-->
    <file value="logs/logfile.txt"/>
    <!--追加到原文件-->
    <appendToFile value="true"/>
    <rollingStyle value="Composite"/>
    <datePattern value="yyyy-MM-dd"/>
    <!--最大变换数量,-1为不限制-->
    <maxSizeRollBackups value="-1" />
    <!--最大文件大小-->
    <maximumFileSize value="100MB" />
    <layout type="log4net.Layout.PatternLayout,log4net">
      <param name="ConversionPattern" value="%d{ABSOLUTE} %c{1}(%L) %M [%-5p] - %m%n"/>
    </layout>
  </appender>
  <root>
    <priority value="Info"/>
    <appender-ref ref="console"/>
    <appender-ref ref="trace"/>
    <appender-ref ref="rolling"/>
  </root>
  <!--Name值为启动层的名称-->
  <logger name="Test">
    <priority value="Info"/>
  </logger>
</log4net>

三,在Global.asax文件中的Application_Start()方法的结尾处添加,读取Log的配置文件

XmlConfigurator.ConfigureAndWatch(new FileInfo(Server.MapPath("log4net.xml")));

 

 

 

在AssemblyInfo.cs添加,[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.xml", Watch = true)]

 

四,添加using log4net 执行调用输出

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Test.Models.View.HomeModel;
using Test.Models.Entities;
using log4net;

namespace Test.Controllers
{
    public class HomeController : Controller
    {
        protected static readonly ILog Log = LogManager.GetLogger(typeof(MvcApplication));
        public ActionResult test()
        {
            string cc = "111";
            Log.FatalFormat("{0}", cc);
            return View();
        }

    }
}

 

posted @ 2017-04-01 12:16  叶丶梓轩  阅读(697)  评论(0编辑  收藏  举报