我们在做开发的时候,需要把一些信息记录下来,方便问题排查、数据分析和统计。通常我们使用log4net作为logging的工具,但是大部分时候需要加以封装,以便更加方便的使用,并且不妨碍主业务程序的运行。下面就是一个异步logging的例子,关键在于:

  1. 简洁:不做过度封装,能满足需要的就是做好的,“done is better than perfect”;
  2. 异步:所有的信息都以异步的方式进行记录,不会对主业务逻辑造成任何的block。

首先,在一个新建的工程里引用log4net.dll,并且进行简单的封装。

 using System;
using System.Diagnostics;
using System.IO;
using log4net; [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)] namespace Log
{
public partial class CommonLogging
{
private const string StringNewLineString = "-------------------------------------------------------"; private static ILog log; static CommonLogging()
{
log = LogManager.GetLogger("common");
StartLogThread();
} public static void Info(string message)
{
AddLog(message);
} public static void Info(string message, Exception ex)
{
AddLog(message, LogType.Info, ex);
} public static void InfoLine(string message)
{
AddLogFormat("{0}\r\n{1}", LogType.Info, null, StringNewLineString, message);
} public static void Warn(string message)
{
AddLog(message, LogType.Warn);
} public static void Warn(string message, Exception ex)
{
AddLog(message, LogType.Warn, ex);
} public static void Debug(string message)
{
AddLog(message, LogType.Debug);
} public static void Debug(string message, Exception ex)
{
AddLog(message, LogType.Debug, ex);
} public static void Error(string message)
{
AddLog(message, LogType.Error);
} public static void Error(string message, Exception ex)
{
if (null == ex)
{
Error(message);
return;
} AddLog(message, LogType.Error, ex);
} public static void Fatal(string message)
{
AddLog(message, LogType.Fatal);
} public static void Fatal(string message, Exception ex)
{
AddLog(message, LogType.Fatal, ex);
} public static void InfoFormat(string format, params string[] args)
{
AddLogFormat(format, LogType.Info, null, args);
} public static void ErrorFormat(string format, params string[] args)
{
AddLogFormat(format, LogType.Error, null, args);
} public static void ErrorFormat(string format, Exception ex, params string[] args)
{
AddLogFormat(format, LogType.Error, ex, args);
} public static void WatchToInfoLog(string message, Action action)
{
Stopwatch sw = Stopwatch.StartNew();
Info(string.Format("start to {0}", message));
action();
sw.Stop();
Info(string.Format("{0} completed..., cost: {1}", message, sw.Elapsed.TotalSeconds));
} public static bool CatchLog(Action action, string errorMsg, bool isThrowException = false)
{
if (null == action)
{
return true;
} try
{
action();
return true;
}
catch (Exception ex)
{
Error(errorMsg, ex); if (isThrowException)
{
throw;
} return false;
}
} private static string GetLogFileName(string tname)
{
string name;
string basedir = AppDomain.CurrentDomain.BaseDirectory;
int pos = basedir.IndexOf("\\inetpub\\");
if (pos < )
{
// we are not running under an inetpub dir, log underneath the base dir
string separator = basedir.EndsWith("\\") ? null : "\\";
name = AppDomain.CurrentDomain.BaseDirectory + separator + @"logs\" + "nevmiss" + tname + ".log";
}
else
{
// we're running on an IIS server, so log under the logs directory so we can share it
name = basedir.Substring(, pos + ) + "logs" + Path.DirectorySeparatorChar + "nevmiss_" + tname + ".log";
} return name;
}
}
}

CommonLogging

使用一个partial类来进行扩展:

 using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks; namespace Log
{
public partial class CommonLogging
{
private static ConcurrentQueue<LoggingModel> messageQueue; private static Thread thread; private static void StartLogThread()
{
messageQueue = new ConcurrentQueue<LoggingModel>();
thread = new Thread(InternalWriteLog);
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true; thread.Start();
} private static void AddLog(string message, LogType type = LogType.Info, Exception ex = null)
{
messageQueue.Enqueue(new LoggingModel(message, type, ex));
CommonLogging.Trigger();
} private static void AddLogFormat(string format, string arg0, LogType type = LogType.Info, Exception ex = null)
{
try
{
messageQueue.Enqueue(new LoggingModel(string.Format(format, arg0), type, ex));
CommonLogging.Trigger();
}
catch (Exception exception)
{
AddLog(string.Format("Add Log Format error, format string:'{0}' , arg0:{1}.", format, arg0), LogType.Error, exception);
}
} private static void AddLogFormat(string format, LogType type = LogType.Info, Exception ex = null, params string[] args)
{
try
{
messageQueue.Enqueue(new LoggingModel(string.Format(format, args), type, ex));
CommonLogging.Trigger();
}
catch (Exception exception)
{
AddLog(
string.Format("Add Log Format error,format:'{0}', arg:{1}.", format, null == args ? null : string.Join(" , ", args)),
LogType.Error,
exception);
}
} public static void Trigger()
{
if (IsProcessing)
{
return;
}
else
{
Task.Factory.StartNew(() =>
{
InternalWriteLog();
});
}
} private volatile static bool IsProcessing = false;
public static void InternalWriteLog()
{
LoggingModel model;
while (messageQueue.TryDequeue(out model))
{
IsProcessing = true; switch (model.MessageType)
{
case LogType.Info:
{
log.Info(model.Message, model.Exception);
}
break;
case LogType.Error:
{
log.Error(model.Message, model.Exception);
}
break;
case LogType.Warn:
{
log.Warn(model.Message, model.Exception);
}
break;
case LogType.Debug:
{
log.Debug(model.Message, model.Exception);
}
break;
default:
break;
} model.Dispose();
} IsProcessing = false;
}
}
}

CommonLogging

用到的LoggingModel:

 using System;

 namespace Log
{
internal struct LoggingModel : IDisposable
{
private string message;
private LogType messageType;
private Exception exception; public Exception Exception
{
get { return this.exception; }
set { this.exception = value; }
} internal LogType MessageType
{
get { return this.messageType; }
set { this.messageType = value; }
} public string Message
{
get { return this.message; }
set
{
this.message = value;
}
} public LoggingModel(string message, bool isError = false, Exception ex = null)
{
this.message = string.Format("[{0}],{1}", DateTime.UtcNow.ToString("HH:mm:ss,fff"), message);
this.messageType = isError ? LogType.Error : LogType.Info;
this.exception = ex;
} public LoggingModel(string message, LogType type = LogType.Info, Exception ex = null)
{
this.message = string.Format("[{0}] {1}", DateTime.UtcNow.ToString("HH:mm:ss,fff"), message);
this.messageType = type;
this.exception = ex;
} public void Dispose()
{
this.exception = null;
this.message = null;
}
} internal enum LogType
{
Debug = , Info = , Warn = , Error = , Fatal = ,
}
}

LoggingModel

其次,在需要使用logging的工程中加入单独的配置文件:

<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger %ndc - %message%newline" />
</layout>
</appender> <appender name="CommonLogAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs\common_"/>
<encoding value="utf-8"/>
<appendToFile value="true"/>
<rollingStyle value="Date"/>
<datePattern value="yyyyMMdd'.log'"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="50MB"/>
<staticLogFileName value="false"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level- %message%newline"/>
</layout>
</appender> <!-- Setup the root category, add the appenders and set the default level -->
<root>
<level value="ALL" />
<appender-ref ref="ConsoleAppender" />
</root> <logger name="common">
<level value="INFO" />
<appender-ref ref="CommonLogAppender" />
</logger>
</log4net>
</configuration>

注意:需要设置log4net.config的属性,使之能够自动拷贝到编译的文件夹中。

并且在app.config或者web.config中指定对应的引用:

<appSettings>
<add key="log4net.Config" value="log4net.config" />
<add key="log4net.Config.Watch" value="True" />
</appSettings>

这样就可以方便地使用logging而不用担心性能的问题啦。

基于log4net自定义异步logging组件的更多相关文章

  1. 基于uniapp自定义Navbar+Tabbar组件「兼容H5+小程序+App端Nvue」

    uni-app跨端自定义navbar+tabbar组件|沉浸式导航条|仿咸鱼凸起标签栏 在跨端项目开发中,uniapp是个不错的框架.采用vue.js和小程序语法结构,使得入门开发更容易.拥有非常丰富 ...

  2. 基于log4net的日志组件扩展封装,实现自动记录交互日志 XYH.Log4Net.Extend(微服务监控)

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

  3. 011-多线程-基础-基于AbstractQueuedSynchronizer自定义同步组件

    一.概述 队列同步器AbstractQueuedSynchronizer,是用来构建锁或者其他同步组件的基础框架. 1.1.自定义独占锁同步组件 设计一个同步工具:该工具在同一时刻,只允许一个线程访问 ...

  4. 基于事件的异步模式——BackgroundWorker

    实现异步处理的方法很多,经常用的有基于委托的方式,今天记录的是基于事件的异步模式.利用BackgroundWorker组件可以很轻松的实现异步处理,并且该组件还支持事件的取消.进度报告等功能.本文以计 ...

  5. 饿了么基于Vue2.0的通用组件开发之路(分享会记录)

    Element:一套通用组件库的开发之路 Element 是由饿了么UED设计.饿了么大前端开发的一套基于 Vue 2.0 的桌面端组件库.今天我们要分享的就是开发 Element 的一些心得. 官网 ...

  6. 实践基于Task的异步模式

    Await 返回该系列目录<基于Task的异步模式--全面介绍> 在API级别,实现没有阻塞的等待的方法是提供callback(回调函数).对于Tasks来说,这是通过像ContinueW ...

  7. 基于Task的异步模式的定义

    返回该系列目录<基于Task的异步模式--全面介绍> 命名,参数和返回类型 在TAP(Task-based Asynchronous Pattern)中的异步操作的启动和完成是通过一个单独 ...

  8. artDialog是一个基于javascript编写的对话框组件,它拥有精致的界面与友好的接口

    artDialog是一个基于javascript编写的对话框组件,它拥有精致的界面与友好的接口 自适应内容 artDialog的特殊UI框架能够适应内容变化,甚至连外部程序动态插入的内容它仍然能自适应 ...

  9. Event-based Asynchronous Pattern Overview基于事件的异步模式概览

    https://msdn.microsoft.com/zh-cn/library/wewwczdw(v=vs.110).aspx Applications that perform many task ...

随机推荐

  1. [jQuery]使用jQuery.Validate进行客户端验证(初级篇)

    以前在做项目的时候就有个很大心病,就是微软的验证控件,虽然微软的验证控件可以帮我们完成大部分的验证,验证也很可靠上手也很容易,但是我就是觉得不爽,主要理由有以下几点: 1.拖控件太麻烦,这个是微软控件 ...

  2. ubuntu - 14.04,安装JDK1.8(JAVA程序需要的开发、运行环境)

    一,如何删除低版本的open JDK? 在ubuntn的软件中心中,如果输入"java",我们会看到open JDK,但是最高版本是1.7,也有1.6版本的,如果我们安装上去,可能 ...

  3. iOS的iPhone屏幕尺寸、分辨率、PPI和使用123倍图

  4. POI2011 Tree Rotations

    POI2011 Tree Rotations 给定一个n<=2e5个叶子的二叉树,可以交换每个点的左右子树.要求前序遍历叶子的逆序对最少. 由于对于当前结点x,交换左右子树,对于范围之外的逆序对 ...

  5. web安全-点击劫持

    web安全-点击劫持 opacity=0 iframe是目标网站 被内嵌了 1.用户亲手操作 盗取用户 视频 2.用户不知情 >* 引导点击 其实点击的是覆盖在下面opacity=0的ifram ...

  6. cookie和session的使用和区别

    cookie:存储在浏览器 存值:setcookie("名字",值,过期时间.秒,哪一个文件夹)//文件夹不写一般默认整个网站都可以 setcookie("usernam ...

  7. zabbix监控tcp连接数的脚本!!

    #!/bin/bash #this script is used to get tcp and udp connetion status #tcp status metric=$ tmp_file=/ ...

  8. pytorch contiguous的使用

    contiguous一般与transpose,permute,view搭配使用 即使用transpose或permute进行维度变换后,调用contiguous,然后方可使用view对维度进行变形. ...

  9. html td 限制 高度 和 宽度

    td 要设置成 display : block td 里面的span 自动换行.. <td style="max-width: 150px;overflow-y:scroll;disp ...

  10. SharePoint开发中可能用到的各种Context(上下文)

    转载: http://www.cnblogs.com/erucy/archive/2012/08/25/2655600.html 电脑正在以无比慢的速度从微软网站上安装Office Component ...