背景:

  随着公司的项目不断的完善,功能越来越复杂,服务也越来越多(微服务),公司迫切需要对整个系统的每一个程序的运行情况进行监控,并且能够实现对自动记录不同服务间的程序调用的交互日志,以及通一个服务或者项目中某一次执行情况的跟踪监控

       根据log4net的现有功能满足不了实际需求,所以需要以log4net为基础进行分装完善,现在分装出了一个基础的版本,如有不妥之处,多多指点
功能简介:
  该组件是在log4net的基础上,进行了一定的扩展封装实现的自动记录交互日志功能
  该组件的封装的目的是解决一下几个工作中的实际问题
  1、对记录的日志内容格式完善
  2、微服务项目中,程序自动记录不同服务间的调用关系,以及出参、入参、执行时间等
  3、同一项目中,不同方法及其层之间的调用关系等信息
  4、其最终目的就是,实现对系统的一个整体监控

主要封装扩展功能点:
1、通过对log4net进行扩展,能够自定义了一些日志格式颜色内容等
2、通过代理+特性的方式,实现程序自动记录不同服务间,以及同一程序间的相互调用的交互日志
3、采用队列的方式实现异步落地日志到磁盘文件

 

主要核心代码示例,具体的详细代码,我已经上传至githut开源项目中,如有需要可以下载了解

github源码地址:https://github.com/xuyuanhong0902/xyh.log4net.extend.git

代理实现自动记录方法调用的详细日志

   /// <summary>
    /// xyh代理实现类.
    /// </summary>
    public class xyhaopproxy : realproxy
    {
        /// <summary>
        /// 构造函数.
        /// </summary>
        /// <param name="target">目标类型.</param>
        public xyhaopproxy(type target)
            : base(target)
        {
        }

        /// <summary>
        /// 重写代理实现.
        /// </summary>
        /// <param name="msg">代理函数</param>
        /// <returns>返回结果</returns>
        public override imessage invoke(imessage methodinvoke)
        {
            //// 方法开始执行时间
            datetime executestarttime = system.datetime.now;

            //// 方法执行结束时间
            datetime executeendtime = system.datetime.now;

            imessage message = null;
            imethodcallmessage call = methodinvoke as imethodcallmessage;
            object[] customattributearray = call.methodbase.getcustomattributes(false);
            call.methodbase.getcustomattributes(false);

            try
            {
                // 前处理.
                list<iaopaction> proactionlist = this.initaopaction(customattributearray, advicetype.before);

                //// 方法执行开始记录日志
                if (proactionlist != null && proactionlist.count > 0  )
                {
                    foreach (iaopaction item in proactionlist)
                    {
                        imessage premessage = item.preprocess(methodinvoke, base.getunwrappedserver());
                        if (premessage != null)
                        {
                            message = premessage;
                        }
                    }

                    if (message != null)
                    {
                        return message;
                    }
                }

                message = proessed(methodinvoke);

                // 后处理.
                proactionlist = this.initaopaction(customattributearray, advicetype.around);

                //// 方法执行结束时间
                executeendtime = system.datetime.now;

                //// 方法执行结束记录日志
                if (proactionlist != null && proactionlist.count > 0)
                {
                    foreach (iaopaction item in proactionlist)
                    {
                        item.postprocess(methodinvoke, message, base.getunwrappedserver(), executestarttime, executeendtime);
                    }
                }
            }
            catch (exception ex)
            {
                //// 方法执行结束时间
                executeendtime = system.datetime.now;

                // 异常处理.吃掉异常,不影响主业务
                list<iaopaction> proactionlist = this.initaopaction(customattributearray, advicetype.around);
                if (proactionlist != null && proactionlist.count > 0)
                {
                    foreach (iaopaction item in proactionlist)
                    {
                        item.exceptionprocess(ex, methodinvoke, base.getunwrappedserver(), executestarttime, executeendtime);
                    }
                }
            }

            return message;
        }

        /// <summary>
        /// 处理方法执行.
        /// </summary>
        /// <param name="methodinvoke">代理目标方法</param>
        /// <returns>代理结果</returns>
        public virtual imessage proessed(imessage methodinvoke)
        {
            imessage message;
            if (methodinvoke is iconstructioncallmessage)
            {
                message = this.processconstruct(methodinvoke);
            }
            else
            {
                message = this.processinvoke(methodinvoke);
            }
            return message;
        }

        /// <summary>
        /// 普通代理方法执行.
        /// </summary>
        /// <param name="methodinvoke">代理目标方法</param>
        /// <returns>代理结果</returns>
        public virtual imessage processinvoke(imessage methodinvoke)
        {
            imethodcallmessage callmsg = methodinvoke as imethodcallmessage;
            object[] args = callmsg.args;   //方法参数                 
            object o = callmsg.methodbase.invoke(base.getunwrappedserver(), args);  //调用 原型类的 方法       

            return new returnmessage(o, args, args.length, callmsg.logicalcallcontext, callmsg);   // 返回类型 message
        }

        /// <summary>
        /// 构造函数代理方法执行.
        /// </summary>
        /// <param name="methodinvoke">代理目标方法</param>
        /// <returns>代理结果</returns>
        public virtual imessage processconstruct(imessage methodinvoke)
        {
            iconstructioncallmessage constructcallmsg = methodinvoke as iconstructioncallmessage;
            iconstructionreturnmessage constructionreturnmessage = this.initializeserverobject((iconstructioncallmessage)methodinvoke);
            realproxy.setstubdata(this, constructionreturnmessage.returnvalue);

            return constructionreturnmessage;
        }

        /// <summary>
        /// 代理包装业务处理.
        /// </summary>
        /// <param name="customattributearray">代理属性</param>
        /// <param name="advicetype">处理类型</param>
        /// <returns>结果.</returns>
        public virtual list<iaopaction> initaopaction(object[] customattributearray, advicetype advicetype)
        {
            list<iaopaction> actionlist = new list<iaopaction>();
            if (customattributearray != null && customattributearray.length > 0)
            {
                foreach (attribute item in customattributearray)
                {
                    xyhmethodattribute methodadviceattribute = item as xyhmethodattribute;
                    if (methodadviceattribute != null && (methodadviceattribute.advicetype == advicetype))
                    {
                        if (methodadviceattribute.processtype == processtype.none)
                        {
                            continue;
                        }

                        if (methodadviceattribute.processtype == processtype.log)
                        {
                            actionlist.add(new logaopactionimpl());
                            continue;
                        }
                    }
                }
            }

            return actionlist;
        }
    }

  类注解

  /// <summary>
    /// xyh代理属性[作用于类].
    /// ************************************
    /// [decoratesymbol] class classname
    /// ************************************
    /// </summary>
    [attributeusage(attributetargets.class, allowmultiple = false)]
    public class xyhaopattribute : proxyattribute
    {
        public xyhaopattribute()
        {
        }

        public override marshalbyrefobject createinstance(type servertype)
        {
            xyhaopproxy realproxy = new xyhaopproxy(servertype);
            return realproxy.gettransparentproxy() as marshalbyrefobject;
        }
    }

  队列实现异步日志落地到磁盘文件

namespace xyh.log4net.extend
{
    /// <summary>
    /// 通过队列的方式实现异步记录日志
    /// </summary>
    public sealed class extendlogqueue
    {
        /// <summary>
        /// 记录消息 队列
        /// </summary>
        private readonly concurrentqueue<logmessage> extendlogque;

        /// <summary>
        /// 信号
        /// </summary>
        private readonly manualresetevent extendlogmre;

        /// <summary>
        /// 日志
        /// </summary>
        private static extendlogqueue _flashlog = new extendlogqueue();

        /// <summary>
        /// 构造函数
        /// </summary>
        private extendlogqueue()
        {
            extendlogque = new concurrentqueue<logmessage>();
            extendlogmre = new manualresetevent(false);
        }

        /// <summary>
        /// 单例实例
        /// </summary>
        /// <returns></returns>
        public static extendlogqueue instance()
        {
            return _flashlog;
        }

        /// <summary>
        /// 另一个线程记录日志,只在程序初始化时调用一次
        /// </summary>
        public void register()
        {
            thread t = new thread(new threadstart(writelogdispatch));
            t.isbackground = false;
            t.start();
        }

        /// <summary>
        /// 从队列中写日志至磁盘
        /// </summary>
        private void writelogdispatch()
        {
            while (true)
            {

                //// 如果队列中还有待写日志,那么直接调用写日志
                if (extendlogque.count > 0)
                {
                    //// 根据队列写日志
                    writelog();

                    // 重新设置信号
                    extendlogmre.reset();
                }

                //// 如果没有,那么等待信号通知
                extendlogmre.waitone();
            }
        }

        /// <summary>
        /// 具体调用log4日志组件实现
        /// </summary>
        private void writelog()
        {
            logmessage msg;
            // 判断是否有内容需要如磁盘 从列队中获取内容,并删除列队中的内容
            while (extendlogque.count > 0 && extendlogque.trydequeue(out msg))
            {
                new loghandlerimpl(loghandlermanager.getilogger(msg.logserialnumber)).writelog(msg);
            }
        }

        /// <summary>
        /// 日志入队列
        /// </summary>
        /// <param name="message">日志文本</param>
        /// <param name="level">等级</param>
        /// <param name="ex">exception</param>
        public  void enqueuemessage(logmessage logmessage)
        {
            //// 日志入队列
            extendlogque.enqueue(logmessage);

            // 通知线程往磁盘中写日志
            extendlogmre.set();
        }
    }
}

  自定义扩展log4net日志格式内容

namespace xyh.log4net.extend
{
    /// <summary>
    /// 自定义布局(对log2net日志组件的布局自定义扩展).
    /// </summary>
    public class handlerpatternlayout : patternlayout
    {
        /// <summary>
        /// 构造函数.
        /// </summary>
        public handlerpatternlayout()
        {
            ///// 机器名称
            this.addconverter("logmachinecode", typeof(logmachinecodepatternconvert));

            //// 方法名称
            this.addconverter("methodname", typeof(logmethodnamepatternconvert));

            //// 方法入参
            this.addconverter("methodparam", typeof(logmethodparamconvert));

            //// 方法出参
            this.addconverter("methodresult", typeof(logmethodresultconvert));

            //// 程序名称
            this.addconverter("logprojectname", typeof(logprojectnamepatternconvert));

            //// ip 地 址
            this.addconverter("logipaddress", typeof(logserviceippatternconvert));

            //// 日志编号
            this.addconverter("loguniquecode", typeof(loguniquepatternconvert));

            //// 日志序列号
            this.addconverter("logserialnumber", typeof(logserialnumberpatternconvert));

            //// 调用路径
            this.addconverter("invokename", typeof(loginvokenamepatternconvert));

            //// 执行开始时间
            this.addconverter("executestarttime", typeof(executestarttimepatternconvert));

            //// 执行结束时间
            this.addconverter("executeendtime", typeof(executeendtimepatternconvert));

            //// 执行时间
            this.addconverter("executetime", typeof(executetimepatternconvert));
        }
    }
}

  

 

使用说明:
第一步:需要dll文件引用
需要引用两个dell文件:
jeson序列化:newtonsoft.json.dll
log4net组件:log4net.dll
log3net扩展组件:xyh.log4net.extend.dll

第二步:log4配置文件配置
主要配置日志的存储地址,日志文件存储格式、内容等
下面,给一个参考配置文件,具体的配置可以根据实际需要自由配置,其配置方式很log4net本身的配置文件一样,在此不多说

<log4net>
  <root>
    <!-- 定义记录的日志级别[none、fatal、error、warn、debug、info、all]-->
    <level value="all"/>
    <!-- 记录到什么介质中-->
    <appender-ref ref="loginfofileappender"/>
    <appender-ref ref="logerrorfileappender"/>
  </root>
  <!-- name属性指定其名称,type则是log4net.appender命名空间的一个类的名称,意思是,指定使用哪种介质-->
  <appender name="loginfofileappender" type="log4net.appender.rollingfileappender">
    <!-- 输出到什么目录-->
    <param name="file" value="log\\loginfo\\"/>
    <!-- 是否覆写到文件中-->
    <param name="appendtofile" value="true"/>
    <!-- 单个日志文件最大的大小-->
    <param name="maxfilesize" value="10240"/>
    <!-- 备份文件的个数-->
    <param name="maxsizerollbackups" value="100"/>
    <!-- 是否使用静态文件名-->
    <param name="staticlogfilename" value="false"/>
    <!-- 日志文件名-->
    <param name="datepattern" value="yyyymmdd".html""/>
    <param name="rollingstyle" value="date"/>
    <!--布局-->
    <layout type="xyh.log4net.extend.handlerpatternlayout">
      <param name="conversionpattern" value="<hr color=blue>%n%n
                                             日志编号:%property{loguniquecode}  <br >%n
                                             日志序列:%property{logserialnumber} <br>%n
                                             机器名称:%property{logmachinecode} <br>%n
                                             ip 地 址:%property{logipaddress} <br>%n
                                             开始时间:%property{executestarttime} <br>%n
                                             结束时间:%property{executeendtime} <br>%n
                                             执行时间:%property{executetime} <br>%n
                                             程序名称:%property{logprojectname} <br>%n
                                             方法名称:%property{methodname} <br>%n
                                             方法入参:%property{methodparam} <br>%n
                                             方法出参:%property{methodresult} <br>%n
                                             日志信息:%m <br >%n
                                             日志时间:%d <br >%n
                                             日志级别:%-5p <br >%n
                                             异常堆栈:%exception <br >%n
                                             <hr size=1 >"/>
    </layout>
  </appender>
  <!-- name属性指定其名称,type则是log4net.appender命名空间的一个类的名称,意思是,指定使用哪种介质-->
  <appender name="logerrorfileappender" type="log4net.appender.rollingfileappender">
    <!-- 输出到什么目录-->
    <param name="file" value="log\\logerror\\"/>
    <!-- 是否覆写到文件中-->
    <param name="appendtofile" value="true"/>
    <!-- 备份文件的个数-->
    <param name="maxsizerollbackups" value="100"/>
    <!-- 单个日志文件最大的大小-->
    <param name="maxfilesize" value="10240"/>
    <!-- 是否使用静态文件名-->
    <param name="staticlogfilename" value="false"/>
    <!-- 日志文件名-->
    <param name="datepattern" value="yyyymmdd".html""/>
    <param name="rollingstyle" value="date"/>
    <!--布局-->
    <layout type="xyh.log4net.extend.handlerpatternlayout">
      <param name="conversionpattern" value="<hr color=red>%n
                                             日志编号:%property{loguniquecode}  <br >%n
                                             日志序列:%property{logserialnumber} <br>%n
                                             机器名称:%property{logmachinecode} <br>%n
                                             ip 地 址: %property{logipaddress} <br>%n
                                             程序名称:%property{logprojectname} <br>%n
                                             方法名称:%property{methodname}<br>%n
                                             方法入参:%property{methodparam} <br>%n
                                             方法出参:%property{methodresult} <br>%n
                                             日志信息:%m <br >%n
                                             日志时间:%d <br >%n
                                             日志级别:%-5p <br >%n
                                             异常堆栈:%exception <br >%n
                                             <hr size=1 >"/>
    </layout>
    <filter type="log4net.filter.levelrangefilter">
      <levelmin value="error"/>
      <levelmax value="fatal"/>
    </filter>
  </appender>
</log4net>

  

第三步:在global.asax文件中注册消息队列
protected void application_start()
{
arearegistration.registerallareas();
filterconfig.registerglobalfilters(globalfilters.filters);
routeconfig.registerroutes(routetable.routes);
bundleconfig.registerbundles(bundletable.bundles);

////注册日志队列
extendlogqueue.instance().register();
}

第四步:在global.asax文件中生成处理日志序列号
/// <summary>
/// 每一个请求执行开始
/// </summary>
protected void session_start() {
//// 记录获取创建每一个请求的序列号
/// 如果调用放传递了序列号,那么就直接去调用放传递的序列号
/// 如果调用放未传递,那么则生成一个序列号
/// 这样,在一次请求的头部传递一个该请求的唯一序列号,并在以后的每一个请求都一直传递下去
/// 这样,就能够通过这个序列号把每一次请求之间的服务或者方法调用关系串联起来
string[] serialnumber = request.headers.getvalues(“serialnumber”);
if (serialnumber!=null && serialnumber.length>0 && !string.isnullorempty(serialnumber[0]))
{
session[“logserialnumber”] = serialnumber[0];
}
else
{
session[“logserialnumber”] = guid.newguid().tostring().replace(“-“, “”).toupper();
}
}

第五步:在需要自动记录日志的方法类上加上对应的注解

//// 在需要自动记录日志的类上加上 xyhaop注解
[xyhaop]
public class class2: calssadd
{
//// 需要记录自动记录交互日志的方法注解 processtype.log

//// 同时该类还必须继承contextboundobject

[xyhmethod(processtype.log)]
public int addnum(int num1, int num2)
{
}
//// 需要记录自动记录交互日志的方法注解 processtype.none,其实不加注解也不会记录日志
[xyhmethod(processtype.none)]
public int subnum(int num1, int num2)
{
}
}

第六步:完成上面五步已经能够实现自动记录交互日志了,

 但是在实际使用中我们也会手动记录一些日志,本插件也支持手动记录日志的同样扩展效果

目前支持以下6中手动记录日志的重载方法基于log4net的日志组件扩展分装,实现自动记录交互日志 xyh.log4net.extend

 /// <summary>
    /// 记录日志扩展入口
    /// </summary>
    public class xyhlogoperator
    {
        /// <summary>
        /// 添加日志.
        /// </summary>
        /// <param name="message">日志信息对象</param>
        public static void writelog(object message)
        {
            new messageintoqueue().writelog(message);
        }

        /// <summary>
        /// 添加日志.
        /// </summary>
        /// <param name="message">日志信息对象</param>
        /// <param name="level">日志信息级别</param>
        public static void writelog(object message, loglevel level)
        {
            new messageintoqueue().writelog(message, level);
        }

        /// <summary>
        /// 添加日志.
        /// </summary>
        /// <param name="message">日志信息对象</param>
        /// <param name="level">日志信息级别</param>
        /// <param name="exception">异常信息对象</param>
        public static void writelog(object message, exception exception)
        {
            new messageintoqueue().writelog(message, exception);
        }

        /// <summary>
        /// 添加日志.
        /// </summary>
        /// <param name="message">日志信息对象</param>
        /// <param name="methodname">方法名</param>
        /// <param name="methodparam">方法入参</param>
        /// <param name="methodresult">方法请求结果</param>
        public static void writelog(object message, string methodname, object methodparam, object methodresult)
        {
            new messageintoqueue().writelog(message, methodname, methodparam, methodresult);
        }

        /// <summary>
        /// 添加日志.
        /// </summary>
        /// <param name="message">日志信息对象</param>
        /// <param name="methodname">方法名</param>
        /// <param name="methodparam">方法入参</param>
        /// <param name="methodresult">方法请求结果</param>
        /// <param name="level">日志记录级别</param>
        public static void writelog(object message, string methodname, object methodparam, object methodresult, loglevel level)
        {
            new messageintoqueue().writelog(message, methodname, methodparam, methodresult, level);
        }

        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="extendloginfor">具体的日志消息model</param>
        public static void writelog(logmessage extendloginfor)
        {
            new messageintoqueue().writelog(extendloginfor);
        }
    }
}

  

手动记录日志示例:

object message = “一个参数日志记录单元测试”; // todo: 初始化为适当的值
xyhlogoperator.writelog(message);

如有问题,欢迎qq随时交流
qq:1315597862

github源码地址:https://github.com/xuyuanhong0902/xyh.log4net.extend.git