ASP.NET MVC4 Web项目中使用Log4Net记录日志到文件和数据库。

下载与.netframework版本向对应的log4net.dll ,然后添加引用。下载地址:http://logging.apache.org/log4net/download_log4net.cgi

下载:log4net-2.0.8-bin-newkey.zip,然后找到对应的版本的DLL.

 

1.新建一个空的mvc4应用项目。

2.新建一个log4net.config配置文件,数据库的连接字符串改一下。

<?xml version="1.0" encoding="utf-8" ?>

<log4net>
    <!--定义输出到文件中-->
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
        <!--定义文件存放位置-->
        <file value="log\\"/>
        <appendToFile value="true"/>
        <rollingStyle value="Date"/>
        <datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.txt'"/>
        <staticLogFileName value="false"/>
        <param name="MaxSizeRollBackups" value="1000"/>
        <layout type="log4net.Layout.PatternLayout">
            <!--输出格式-->
            <conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别:%-5level %n出错类:%logger property: [%property{NDC}] - %n错误描述:%message%newline"/>
        </layout>
    </appender>

    <!--定义输出到SQL Server数据库中-->
    <!--  
    在SQL Server中创建表的SQL语句  
    CREATE TABLE [dbo].[Log] (  
    [Id] [int] IDENTITY (1, 1) NOT NULL,  
    [Date] [datetime] NOT NULL,  
    [Thread] [varchar] (255) NOT NULL,  
    [Level] [varchar] (50) NOT NULL,  
    [Logger] [varchar] (255) NOT NULL,  
    [Message] [varchar] (4000) NOT NULL,  
    [Exception] [varchar] (2000) NULL  
);  
    -->

    <appender name="AdoNetAppenderSQLServer" type="log4net.Appender.AdoNetAppender">
        <bufferSize value="1" />
        <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        <connectionString value="Data Source=LJJ-FF\LJJ;Initial Catalog=TestMvc;User ID=sa;Password=111111" />
        <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
        <parameter>
            <parameterName value="@log_date" />
            <dbType value="DateTime" />
            <layout type="log4net.Layout.RawTimeStampLayout" />
        </parameter>
        <parameter>
            <parameterName value="@thread" />
            <dbType value="String" />
            <size value="255" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%thread" />
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@log_level" />
            <dbType value="String" />
            <size value="50" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%level" />
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@logger" />
            <dbType value="String" />
            <size value="255" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%logger" />
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@message" />
            <dbType value="String" />
            <size value="4000" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%message" />
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@exception" />
            <dbType value="String" />
            <size value="2000" />
            <layout type="log4net.Layout.ExceptionLayout" />
        </parameter>
    </appender>

    <root>
        <level value="ALL" />
        <!--文件形式记录日志-->
        <appender-ref ref="RollingLogFileAppender"/>-->
        <!--SQL Server数据库形式记录日志-->
        <appender-ref ref="AdoNetAppenderSQLServer"/>
    </root>

</log4net>

3.在web.config中的<configuration>节点下面添加:

<configSections>
<section name="log4net"  type="System.Configuration.IgnoreSectionHandler"/>
</configSections>

4.在Global.asax下面添加下面代码:

  //应用程序启动时,自动加载配置log4Net  
            XmlConfigurator.Configure();  

5.在AssemblyInfo.cs 下面添加代码:

//[assembly: log4net.Config.XmlConfigurator(Watch = true)]
//注意: ConfigFile 可以指定相对路径 和 绝对路径。 eg: /log/xxxx.log  或者 d://log//xxxx.log
//这句话是把节点单独拆分成log4net.config,这里像下面这样写。
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]
//这个是log4net配置文件节点写在web.config里面用这句话
//[assembly: log4net.Config.XmlConfigurator(Watch = true)]

6.新建LogHelper类:

using log4net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;

namespace MvcLog4netToDataBase
{
    public class LogHelper
    {
        /// <summary>
        /// 调用Log4net写日志,日志等级为 :错误(Error)
        /// </summary>
        /// <param name="logContent">日志内容</param>
        public static void WriteLog(string logContent)
        {
            WriteLog(null, logContent, Log4NetLevel.Error);
        }

        /// <summary>
        /// 调用Log4net写日志
        /// </summary>
        /// <param name="logContent">日志内容</param>
        /// <param name="log4Level">记录日志等级,枚举</param>
        public static void WriteLog(string logContent, Log4NetLevel log4Level)
        {
            WriteLog(null, logContent, log4Level);
        }

        /// <summary>
        /// 调用Log4net写日志
        /// </summary>
        /// <param name="type">类的类型,指定日志中错误的具体类。例如:typeof(Index),Index是类名,如果为空表示不指定类</param>
        /// <param name="logContent">日志内容</param>
        /// <param name="log4Level">记录日志等级,枚举</param>
        public static void WriteLog(Type type, string logContent, Log4NetLevel log4Level)
        {
            ILog log = type == null ? LogManager.GetLogger("") : LogManager.GetLogger(type);

            switch (log4Level)
            {
                case Log4NetLevel.Warn:
                    log.Warn(logContent);
                    break;
                case Log4NetLevel.Debug:
                    log.Debug(logContent);
                    break;
                case Log4NetLevel.Info:
                    log.Info(logContent);
                    break;
                case Log4NetLevel.Fatal:
                    log.Fatal(logContent);
                    break;
                case Log4NetLevel.Error:
                    log.Error(logContent);
                    break;
            }
        }
    }

  

    /// <summary>
    /// log4net 日志等级类型枚举
    /// </summary>
    public enum Log4NetLevel
    {
        [Description("警告信息")]
        Warn = 1,
        [Description("调试信息")]
        Debug = 2,
        [Description("一般信息")]
        Info = 3,
        [Description("严重错误")]
        Fatal = 4,
        [Description("错误日志")]
        Error = 5
    }
}


7.建HomeController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using log4net;

namespace MvcLog4netToDataBase.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            //简单写日志
            LogHelper.WriteLog("简单写日志");
            //写Debug日志
            LogHelper.WriteLog("写Debug日志", Log4NetLevel.Debug);
            //带有类型和日志等级的日志,Index 是类名
            LogHelper.WriteLog(typeof(HomeController), "带有类型和日志等级的日志", Log4NetLevel.Info);
            return View();
        }

    }
}

8.建一个Index视图。

9.运行得出结果:

 

posted on 2018-10-30 11:35  sxjljj  阅读(1512)  评论(0编辑  收藏  举报