PostSharp 结合 log4net 自动记录日志
环境:
VS 2012
PostSharp-4.1.28 (下载地址)https://visualstudiogallery.msdn.microsoft.com/a058d5d3-e654-43f8-a308-c3bdfdd0be4a/file/89212/69/PostSharp-4.1.28.exe
log4net 2.0.3
首先搭建环境:
下载好PostSharp 之后进行安装。之后创建项目
1、引用PoastSharp
PoastSharp引用方式如下:
VS工具 —>> NuGet 程序包管理 —>> 管理解决方案的NuGet程序包 出现如下图:
搜索PostSharp 安装等待...

安装完成之后会在项目的解决方案同级目录下出现下列文件:

同时解决方案里面的项目会自动出现PostSharp的引用、

如果没有自动引用,我们就手动引用下就好了。 根据.NET Framework的版本,选择对应的dll
PostSharp.dll 安装引用已经OK了。
2、log4net安装引用
打开 VS工具 —>> NuGet 程序包管理 —>> 程序包管理器控制台
在控制台中输入 PM> Install-Package log4net (PM> 是已经有了的)敲回车键
然后安心等待...(上面的红色的Error是因为网速比较慢,没有Load出来, 没有关系再来一次)
下面第二次可以看见已经安装成功,并且把我的机器上老版本替换掉了。 干得漂亮!!!

如PostSharp 一样,也会在解决方案下面出现lib文件, 如果项目里面没有引用的就手动引用好了。
接下来开始真正的干活了......
首先配置好log4net.config
下面是我习惯的步骤:
1、在应用程序下创建 App.config 文件

2、修改App.config 文件的内容(直接复制替换好了,详细的配置项就不说明了)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections> <log4net>
<!-- You can add your own appender here. -->
<!-- Define some output appenders -->
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<!--
This appender is used for writing application log.
-->
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<!-- Log file name, you can find the file in the application startup directory. -->
<param name="File" type="log4net.Util.PatternString" value="Log\Client_%date{yyyyMMddHHmmss}.log"/>
<param name="Encoding" value="UTF-8"/>
<param name="AppendToFile" value="true"/>
<param name="MaxSizeRollBackups" value=""/>
<!--
The maximum size of the log file,
when the log file size exceed this size,
a new log.txt will created and the old one will rename to log.txt..
-->
<param name="MaximumFileSize" value="2MB"/>
<param name="RollingStyle" value="Size"/>
<param name="StaticLogFileName" value="true"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date [%thread] %logger %-5level - %message%newline"/>
</layout>
</appender>
<!--
The root logger.
Set the level to log the necessary log information only.
The level can be set to: ALL, DEBUG, INFO, WARN, ERROR, Fatal
The appender-ref can be set the any appender name in this configuration file.
-->
<root>
<level value="ALL"/>
<appender-ref ref="RollingFileAppender"/>
<appender-ref ref="ConsoleAppender"/> </root>
</log4net>
</configuration>
3、接着很重要的一步,不然配置的都白干了...
打开AssemblyInfo.cs文件,在文件最后添加一行代码
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

好的,到此。log4net 已经配置完成。 可以先测试一下log4net 是否可以正常工作
创建一个空的WinForm,添加如下代码
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using log4net; namespace PostSharp.Demo
{
public partial class TestLog4netFrm : Form
{
public static log4net.ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public TestLog4netFrm()
{
InitializeComponent();
} private void TestLog4netFrm_Load(object sender, EventArgs e)
{
_logger.Debug("test log4net ");
}
}
}
然后生成运行。
运行成功之后,关掉Form。 打开bin/Debug 可以看见有一个Log文件夹里面会生成一个日志文件,打开可以看见我们刚才写的 test log4net
好的。 干得漂亮!!! 已经成功一半了。即使不用postSharp也可以完成日常的打Log了。

为了继续完善,把PostSharp使用起来,让它给我们自动的打Log。
1、创建项目 PostSharp.Core ,创建文件TraceAttribute.cs

TraceAttribute.cs 代码如下:(格式可以根据需要自己调整的...)
using System;
using System.Collections.Generic;
using System.Text;
using PostSharp.Aspects;
using PostSharp.Extensibility;
using System.Reflection; namespace PostSharp.Core
{
[Serializable]
public sealed class TraceAttribute : OnMethodBoundaryAspect
{
// Create a logger for use in this class, called only once
private static readonly log4net.ILog _logger; private string _methodName; // These fields are initialized at runtime. They do not need to be serialized.
[NonSerialized]
private int _hashCode; static TraceAttribute()
{
if (!PostSharpEnvironment.IsPostSharpRunning)
{
_logger =
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
}
} // Default constructor, invoked at build time.
public TraceAttribute()
{
// Do nothing
} // Invoked only once at runtime from the static constructor of type declaring the target method.
public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo)
{
_methodName = method.DeclaringType.Name + "." + method.Name;
} // Invoked only once at runtime from the static constructor of type declaring the target method.
public override void RuntimeInitialize(MethodBase method)
{
_hashCode = this.GetHashCode();
} // Invoked at runtime before that target method is invoked.
public override void OnEntry(MethodExecutionArgs args)
{
_logger.DebugFormat(">>> Entry [{0}] {1}", _hashCode, _methodName);
} // Invoked at runtime after the target method is invoked (in a finally block).
public override void OnExit(MethodExecutionArgs args)
{
_logger.DebugFormat("<<< Exit [{0}] {1}", _hashCode, _methodName);
} // Invoked at runtime when there is unhandled exception from the target method
public override void OnException(MethodExecutionArgs args)
{
string expMsg = string.Format("!!! Exception [{0}] {1} {2}", _hashCode, _methodName, args.Exception.Message);
_logger.ErrorFormat(expMsg, args.Exception);
} // Invoked at runtime when await starts in the target method
public override void OnYield(MethodExecutionArgs args)
{
_logger.DebugFormat("--- OnYield [{0}] {1}", _hashCode, _methodName);
} // Invoked at runtime when await resumed in the target method
public override void OnResume(MethodExecutionArgs args)
{
_logger.DebugFormat("--- OnResume [{0}] {1}", _hashCode, _methodName);
}
}
}
2、很重要的一步,PostSharp.Core 项目的 AssemblyInfo.cs 文件也需要在最后加上一句代码。同上
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
好了,到此。 安装,引用,配置已经全部结束。 开始测试...
创建新的Form,(什么都不需要写,就使用Load事件好了)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using log4net;
using PostSharp.Core;
using System.Reflection; namespace PostSharp.Demo
{
public partial class TestPostSharpFrm : Form
{
public static log4net.ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public TestPostSharpFrm()
{
InitializeComponent();
} [Trace]
private void TestPostSharpFrm_Load(object sender, EventArgs e)
{ }
}
}
然后直接运行、可以看见下面就是我们在TraceAttribute.cs 中配置好的输出格式

全部OK。 干的非常漂亮!!!
From需要应用下面的命名空间
using log4net;
using PostSharp.Core;
using System.Reflection;
可以看看编译过后的代码:
1、未使用PostSharp 的代码

2、使用PostSharp 打过标签的代码

不难看出,PostSharp,会在编译之后把Log注入到代码中去。
同时每个方法的执行位置一目了然...
源码下载地址:http://files.cnblogs.com/files/chris-zeng/PostSharp.Demo.rar
PostSharp 结合 log4net 自动记录日志的更多相关文章
- .netcore3.1使用log4net/nlog记录日志
.netcore3.1使用log4net/nlog记录日志 .netcore3.1与2.x之间很是有不少差异的.本来想通过ctrl+c,ctrl+v将在2.2中实现的简单日志记录搬到.netcore3 ...
- SecureCRT配置自动记录日志
很多人用SecureCRT时,希望自动记录日志,一个是方便以后查阅,一个是对自己的操作有个记录.可以看看自己做了什么操作,有时甚至可以看看之前是不是犯了什么错,是个很不错的功能. 设置很简单,还可以根 ...
- SecureCRT使用之自动记录日志功能
自动记录日志功能: 选择"选项"--"全局选项",打开全局选项,在常规设置中找到"默认会话"设置项,点击右侧的"编辑默认设置&qu ...
- SecureCRT自动记录日志
From: http://lzj0470.iteye.com/blog/1189368 今天在推特上看到有人谈起SecureCRT日志记录的问题,貌似很多人都有这习惯 我是开始工作后才使用Secure ...
- 利用Log4net组件记录日志
项目中利用Log4net记录日志还是比较方便的,我也按照网上的一些操作进行了实践 参考文章 1:Log4Net使用指南2:LOG4NET日志配置 组件下载 log4net组件下载 1:设置配置文件,这 ...
- SecureCRT 7.0 如何自动记录日志
设置步骤如下: 1.打开SecureCRT ,在菜单里选择“选项”-->“全局选项” 2.然后选择“常规”--> “默认会话”--> “编辑默认设置” 3.然后选择“日志 ...
- 在Windows中 , 如何用leakdiag “自动”检测内存泄露 (自动记录日志)
一.基本用法 在LeakDiag中选择aaa.exe 然后选择Windows Heap Allocator来跟踪heap的使用,按start开始,等一会按log,然后再stop 会在c:\leakdi ...
- 在类库项目中使用log4net(RollingFileAppender)记录日志
1.创建解决方案 2.创建类库项目 3.根据需要修改命名空间,修改(和/或)添加类到类库 4.引用log4net 5.类库项目根目录下创建leg4net配置文件,如D3CallTriggerPlugi ...
- c#中使用log4net工具记录日志
首先,去官网下载log4net工具 链接http://logging.apache.org/log4net/download_log4net.cgi 目前最新的版本 log4net-1.2.15-bi ...
随机推荐
- solr常见异常解决办法
科普篇 来自百度百科:Solr简介Solr是一个基于Lucene的Java搜索引擎服务器.Solr 提供了层面搜索.命中醒目显示并且支持多种输出格式(包括 XML/XSLT 和 JSON 格式).它易 ...
- Web服务的实质介绍
web应用的实质 众所周知,对于所有的Web应用,本质上其实就是一个socket服务端,用户的浏览器其实就是一个socket客户端 Web应用程序是一种可以通过Web访问的应用程序,程序的最大好处是用 ...
- [Octave] fminunc()
fminunc( FCN, X0); fminunc( FCN, C0, Options); [X, FVEC, INFO, OUTPUT, GRAD, HESS] = fminunc (FCN, . ...
- 好记性不如烂笔头-linux学习笔记5mysql主从复制
mysql主从复制的原理 mysql master服务器,开启bin-log日志,开启IO线程 slave服务器,开启IO线程,开启SQL线程(执行SQL) 1)slave服务器,通过授权用户开启IO ...
- JS计算字符长度、字节数 -- 转
一个汉字在UTF-8编码中占用几个字节? 占用3个字节的范围 U+2E80 - U+2EF3 : 0xE2 0xBA 0x80 - 0xE2 0xBB 0xB3 共 115 个 U+2F00 - U+ ...
- 【Git】二、安装配置
一.Git安装 Linux $ apt-get install libcurl4-gnutls-dev libexpat1-dev gettext \ libz-dev libssl-dev $ ap ...
- PC上对限制在微信客户端访问的html页面进行调试
PC上对微信的html5页面做测试,一般来说需要两个条件:浏览器UA改为微信客户端的UA(打开页面提示请在微信客户端登录就需要修改UA):增加满足html5验证条件的Cookie来进行微信OAUTH验 ...
- Android开发之百度地图的简单使用
越来越多的App运用到了定位,导航的这些功能,其实实现一个自己的百度地图也是非常的简单,这篇博客将会教你简单的实现一个百度地图.看一下效果图: 第一步:要使用百度地图,必须要有百度地图的Key,要获得 ...
- classpath 和 classpath* 的区别:
classpath指的是java代码生成的class的路径. classpath 和 classpath* 区别: classpath:只会到你的class路径中查找找文件; classpath*:不 ...
- UILabel的空格不支持tab键
今天使用模拟器测试,发现有个UITableViewCell的detailTextLabel没有完全显示字符串,结尾是省略号,字符串的值中间显示有空格,如 'Test 01'显示为'Te...' det ...