Log4Net配置

1.添加log4net.dll引用
2.web.config文件加入如下配置

<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="AdoNetAppender_SqlServer" type="log4net.Appender.AdoNetAppender">
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=192.168.18.205;initial catalog=TestDB;User ID=sa;Password=kicpassword" />
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
<parameter>
<parameterName value="@log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout" value="%thread" />
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout" value="%level" />
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout" value="%logger" />
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout" value="%message" />
</parameter>
</appender>
<root>
<level value="ALL"/>     <!--注意ALL一定要大写-->
<appender-ref ref="AdoNetAppender_SqlServer"/>
</root>
</log4net>
3.修改Global.asax文件
        protected void Application_Start()
        {
            //启用log4Net
            log4net.Config.XmlConfigurator.Configure();


            AreaRegistration.RegisterAllAreas();


            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
4.在控制器中加入写日志代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using log4net;


namespace Log4Net_InDatabase.Controllers
{
    public class LogTestController : Controller
    {
        //
        // GET: /LogTest/
        private static ILog log = LogManager.GetLogger(typeof(LogTestController));


        public ActionResult Index()
        {
            return View();
        }


        public ActionResult WriteLog(FormCollection collection)
        {
            log.Debug(collection["LogMsg"]);
            return Content("OK");
        }
    }
}

你可能感兴趣的:(Log4Net配置)