我们在做开发的时候,需要把一些信息记录下来,方便问题排查、数据分析和统计。通常我们使用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. C++11新标准:nullptr关键字

    一.nullptr的意义 1.NULL在C中的定义 #define NULL (void*)0 2.NULL在C++中的定义 #ifndef NULL #ifdef __cplusplus #defi ...

  2. Java50道经典习题-程序25 根据输入求输出

    题目:一个5位数,判断它是不是回文数.即12321是回文数,个位与万位相同,十位与千位相同.分析:分别创建两个数用于判断,一个数为12321,另一个数是12341 分别取出该数的"个十百千万 ...

  3. PHP常用的服务器

    Wordpress够流行了吧,它是一个用PHP编写的强大的博客平台.使用它来架设一个博客平台相关容易,是新手建站比较方便的工具.但是要真正体会Wordpress(以下简称WP)强大,插件是不可少的东西 ...

  4. Locust压力测试使用总结

    https://blog.csdn.net/jojoy_tester/article/details/77926470  参考网址 上次做接口压力测试前一直研究使用jmeter,本以为可以拿来使用了, ...

  5. B - Pie (二分)

    My birthday is coming up and traditionally I'm serving pie. Not just one pie, no, I have a number N ...

  6. [转]10分钟梳理MySQL知识点:揭秘亿级高并发数据库调优与最佳实践法则

    转:https://mp.weixin.qq.com/s/RYIiHAHHStIMftQT6lQSgA 做业务,要懂基本的SQL语句: 做性能优化,要懂索引,懂引擎: 做分库分表,要懂主从,懂读写分离 ...

  7. 【Java】Observer Pattern

    前言 代码来源于生活,更加高于生活.设计模式让我们的生活更加的方便.观测一个东西,盯着一个东西,关注一个公众号,这些东西,如果没有即时通知的话,我们又特别想了解这方面的内容,那么我们除了一直耗着时间找 ...

  8. poj2409(polya 定理模板)

    题目链接:http://poj.org/problem?id=2409 题意:输入 m, n 表示有 m 种颜色,要构造一个长度为 n 的手环,旋转和对称的只算一种,问能组成多少个不同的手环. 思路: ...

  9. Opencv图像连通域

    [摘要] 本文介绍在图像处理领域中较为常用的一种图像区域(Blob)提取的方法——连通性分析法(连通区域标记法). 文中介绍了两种常见的连通性分析的算法:1)Two-pass:2)Seed-Filli ...

  10. CF671A Recycling Bottles 计算几何

    It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can ...