asp.net mvc集成log4net

第一步:在web项目的引用中添加log4net.dll,可以通过Nuget直接下载并安装;第二步:在web项目的web.config配置文件的configuration节点内添加log4net节点,在configSections 节点内添加log4net.dll的配置,如:
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

  </configSections>
 上述配置代码parameter节点的其中四个参数【message,ActionsClick,UserName,UserIP】需要我们自己传递的日志数据,所以这四个节点对应的数据来自于我们自定义类型的属性,并需要对应的工具类去解析,Log4NetApply.MyLayout" > ,MyLayout是自定义的工具解析类名称,Log4NetApply是MyLayout类型的命名空间;第三步:新建日志实体类和解析工具类
namespace Log4NetApply
{
    /// <summary>
    /// 包含了所有的自定字段属性
    /// </summary>
    public class LogContent
    {
        public LogContent(string macAddress, string computerName, string actionsclick, string description)
        {
            UserIP = macAddress;
            UserName = computerName;
            ActionsClick = actionsclick;
            Message = description;
        }

        /// <summary>
        /// 访问IP
        /// </summary>
        public string UserIP { get; set; }

        /// <summary>
        /// 系统登陆用户
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// 动作事件
        /// </summary>
        public string ActionsClick { get; set; }

        /// <summary>
        /// 日志描述信息
        /// </summary>
        public string Message { get; set; }


    }

    public class MyLayout : PatternLayout
    {
        public MyLayout()
        {
            this.AddConverter("property", typeof(LogInfoPatternConverter));
        }
    }

    public class LogInfoPatternConverter : PatternLayoutConverter
    {

        protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
        {
            if (Option != null)
            {
                // Write the value for the specified key
                WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));
            }
            else
            {
                // Write all the key value pairs
                WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
            }
        }
        /// <summary>
        /// 通过反射获取传入的日志对象的某个属性的值
        /// </summary>
        /// <param name="property"></param>
        /// <returns></returns>

        private object LookupProperty(string property, log4net.Core.LoggingEvent loggingEvent)
        {
            object propertyValue = string.Empty;
            PropertyInfo propertyInfo = loggingEvent.MessageObject.GetType().GetProperty(property);
            if (propertyInfo != null)
                propertyValue = propertyInfo.GetValue(loggingEvent.MessageObject, null);
            return propertyValue;
        }
    }

    public class LogHelp
    {
        public static log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    }

}
第四步:在文件Startup.cs中添加注册配置文件的代码
[assembly: OwinStartupAttribute(typeof(WebApplication2.Startup))]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]
namespace WebApplication2
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}
第五步:在Global.asax文件中添加初始化log4net的代码
protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            log4net.Config.XmlConfigurator.Configure();
        }
第六步:测试
public ActionResult Index()
        {
            try
            {
                LogHelp.logger.Info(new LogContent("", "", "Test", "Test"));
                int i = int.Parse("s");
            }
            catch (Exception ex)
            {
                LogHelp.logger.Error(new LogContent("", "", "Test", ex.Message + ";" + ex.StackTrace));
            }

            return View();
        }
上述所有的一切只为得到结果 

相关内容推荐