码迷,mamicode.com
首页 > Web开发 > 详细

log4net VS2012 日志layout自定义,error日志和info日志分别记录到不同文件中

时间:2018-03-08 17:23:20      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:alt   cte   img   param   ons   image   sem   net   标签   

  • 打开VS中“工具”=》“NuGet程序包管理器”=》“管理解决方案的NuGet程序包”菜单

技术分享图片

  • 在“管理NuGet程序包”窗口中,搜索log4net,并安装

 技术分享图片

  • 有时候,我们在日志中需要记录一些业务数据,如operator等信息,我们新建一个类WebMethodLog,来存放log里面需要用到的信息
public class WebMethodLog
    {
        public string operatorNo{get;set;}
        public string operatorName { get; set; }
        public string method { get; set; }
        public string message { get; set; }
    }

技术分享图片

  • 新建WebMethodPatternConvert类
 public class WebMethodPatternConvert : PatternLayoutConverter
    {
        protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
        {
            var webmethod = loggingEvent.MessageObject as WebMethodLog;
            if (webmethod == null) return;
            writer.Write("\r\n------------------------------------------------------------begin----------------------------------------------------------------------");
            writer.Write("\r\nDate: "+System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss,fff"));
            writer.Write(string.Format("\r\nOperator No.: {0}, Operator Name: {1}",webmethod.operatorNo,webmethod.operatorName));
            writer.Write(string.Format("\r\nMethod: {0}", webmethod.method));
            writer.Write("\r\nMessage: "+webmethod.message);
            writer.Write("\r\n------------------------------------------------------------end-------------------------------------------------------------------------");
        } 
    }

技术分享图片

  • 新建WebMethodPatternLayout类
public class WebMethodPatternLayout : log4net.Layout.PatternLayout  
    {
        public WebMethodPatternLayout()
        {
            this.AddConverter("webMethod", typeof(WebMethodPatternConvert));
        }    
    }

技术分享图片

  •  在web.config中进行如下配置:

        1. 在configSections标签中加入如下配置

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

 技术分享图片

         2.  在configuration标签下加入如下配置  

<log4net>
        <root>
            <level value="ALL" />
            <appender-ref ref="InfoAppender" />
            <appender-ref ref="ErrorAppender" />
        </root>
        <logger name="logInfo">
            <level value="Info" />
            <appender-ref ref="InfoAppender" />
        </logger>
        <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender,log4net">
            <param name="File" value="Logs/" />
            <param name="AppendToFile" value="true" />
            <param name="MaxFileSize" value="10240" />
            <param name="MaxSizeRollBackups" value="100" />
            <param name="StaticLogFileName" value="false" />
            <param name="RollingStyle" value="Date" />
            <param name="DatePattern" value="&quot;Logs_&quot;yyyyMMddHH&quot;Info.txt&quot;" />            
            <!--<layout type="log4net.Layout.PatternLayout,log4net">-->
            <layout type="HITTS.Web.Common.WebMethodPatternLayout">
                <param name="ConversionPattern" value="%webMethod" />
            </layout>
            <filter type="log4net.Filter.LevelRangeFilter">  
                <levelMin value="ALL" />  
                <levelMax value="INFO" />  
            </filter> 
        </appender>
        <logger name="logError">
            <level value="Error" />
            <appender-ref ref="ErrorAppender" />
        </logger>
        <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender,log4net">
            <param name="File" value="Logs/" />
            <param name="AppendToFile" value="true" />
            <param name="MaxFileSize" value="10240" />
            <param name="MaxSizeRollBackups" value="100" />
            <param name="StaticLogFileName" value="false" />
            <param name="RollingStyle" value="Date" />
            <param name="DatePattern" value="&quot;Logs_&quot;yyyyMMddHH&quot;Error.txt&quot;" />
            <layout type="HITTS.Web.Common.WebMethodPatternLayout">
                <param name="ConversionPattern" value="%webMethod" />
            </layout>
            <filter type="log4net.Filter.LevelRangeFilter">  
                <levelMin value="ERROR" />  
                <levelMax value="FATAL" />  
            </filter>  
        </appender>
        <appender name="consoleApp" type="log4net.Appender.ConsoleAppender,log4net">
            <layout type="log4net.Layout.PatternLayout,log4net">
                <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
            </layout>
        </appender>
    </log4net>

技术分享图片

  •  在AssemblyInfo.cs文件中增加如下代码:
[assembly:log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]

技术分享图片

  •  测试Log代码
[WebMethod]

public static string LogTest()
{
log4net.ILog log = log4net.LogManager.GetLogger("InfoTest");
string json = "{‘Name‘:‘Cherry‘,‘Age‘:‘27‘}";
log.Info(new WebMethodLog() { operatorNo = employee.EmployeeNo, operatorName = employee.Name, method = HttpContext.Current.Request.Path, message = json });
log.Error(new WebMethodLog() { operatorNo = employee.EmployeeNo, operatorName = employee.Name, method = HttpContext.Current.Request.Path, message = json });
return json;
}

 
  • 测试结果如下:

在Logs文件夹下生成了如下文件:

技术分享图片

技术分享图片

 技术分享图片

 

log4net VS2012 日志layout自定义,error日志和info日志分别记录到不同文件中

标签:alt   cte   img   param   ons   image   sem   net   标签   

原文地址:https://www.cnblogs.com/cherryzhou/p/8528974.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!