环境:

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="10"/>
<!--
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.1.
-->
<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注入到代码中去。

同时每个方法的执行位置一目了然...

  

post sharp 与log4net 结合使用,含执行源码 转拷的更多相关文章

  1. MyBatis(六):SqlSession执行源码分析

    SqlSession执行源码分析 针对以下代码 public class MybatisUtils { private static SqlSessionFactory sqlSessionFacto ...

  2. Tyrion中文文档(含示例源码)

    Tyrion是一个基于Python实现的支持多个WEB框架的Form表单验证组件,其完美的支持Tornado.Django.Flask.Bottle Web框架.Tyrion主要有两大重要动能: 表单 ...

  3. Tyrion 中文文档(含示例源码)

    原文出处: Mr.Seven   Tyrion是一个基于Python实现的支持多个WEB框架的Form表单验证组件,其完美的支持Tornado.Django.Flask.Bottle Web框架.Ty ...

  4. java 动态代理深度学习(Proxy,InvocationHandler),含$Proxy0源码

    java 动态代理深度学习, 一.相关类及其方法: java.lang.reflect.Proxy,Proxy 提供用于创建动态代理类和实例的静态方法.newProxyInstance()返回一个指定 ...

  5. 微信小程序中如何使用WebSocket实现长连接(含完整源码)

    本文由腾讯云技术团队原创,感谢作者的分享. 1.前言   微信小程序提供了一套在微信上运行小程序的解决方案,有比较完整的框架.组件以及 API,在这个平台上面的想象空间很大.腾讯云研究了一番之后,发现 ...

  6. Springboot打包执行源码解析

    一.打包 Springboot打包的时候,需要配置一个maven插件[spring-boot-maven-plugin] <build> <plugins> <plugi ...

  7. JAVA全套资料含视频源码(持续更新~)

    本文旨在免费分享我所搜集到的Java学习资源,所有资源都是通过正规渠道获取,不存在侵权.现在整理分享给有所需要的人. 希望对你们有所帮助!有新增资源我会更新的~大家有好的资源也希望分享,大家互帮互助共 ...

  8. GHO2VMDK转换工具分享含VS2010源码

    平常经常用到虚拟机,每次从gho转换为vmdk时都要输入cmd代码,觉得麻烦,自己动手做了个gho2vmdk转换工具,集成ghost32.exe文件,可以一键转换,省时省事.运行时会将ghost32. ...

  9. Mybatis工作原理(含部分源码)

    MyBatis的初始化 1.读取配置文件,形成InputStream String resource = "mybatis.xml"; // 加载mybatis的配置文件(它也加载 ...

随机推荐

  1. thinkphp 3.2.3 - Dispatcher.class.php 解析(转发器)

    class Dispatcher { public static function dispatch() { $varPath = C('VAR_PATHINFO'); // 's' $varAddo ...

  2. 常用自写函数[更新ing]

    int gcd (int x, int y)//最大公约数 { return y == 0 ? x : gcd( y , x % y ); } int lcm(int x, int y)//最小公倍数 ...

  3. 传送流(TS)的基础知识

    数字电视的TS包和TS流的组成和功能 综合考虑几下几个因素: (1)包的长度不能过短,否则包头开销所占比例过大, 导致传输效率下降 (2)包的长度不能过长,否则在丢失同步的情况下恢复同步的 周期过长, ...

  4. UVALive 4685 Succession 树DP+背包

    一.前言 这道题同样来自于红书P142,作为树DP专题中的一道比较难的题目,A了一天左右的时间,看上去事实证明,这题的难度理我本身的实力还是有些太远了,于是正确的做法应该是分析一下题目之后进行解析什么 ...

  5. Gym 100829S_surf 动态规划的优化

    题目大意是,非你若干个任务,任务分别对应开始时间.预期收益.持续时间三项指标,让你从中选择一个受益最大的方案(没有开始时间相同的任务). 于是,标准状态转移方程应当为,设DP[K]为选择了前K个任务的 ...

  6. RNN教程之-2 LSTM实战

    前言 说出来你们不敢相信,刚才码了半天的字,一个侧滑妈的全没了,都怪这Mac的触摸板太敏感沃日.好吧,不浪费时间了,前言一般都是废话,这个教程要解决的是一个LSTM的实战问题,很多人问我RNN是啥,有 ...

  7. MapReduce实现单词统计

     开发工具:IDEA mapreduce实现思路: Map阶段: a) 从HDFS的源数据文件中逐行读取数据 b) 将每一行数据切分出单词 c) 为每一个单词构造一个键值对(单词,1) d) 将键值对 ...

  8. OpenResty入门

    写一个小例子--输出随机字符串 编写nginx配置文件 location /random { content_by_lua_file /usr/local/openresty/nginx/conf/l ...

  9. leetcode 【 Container With Most Water 】python 实现

    题目: Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, a ...

  10. python矩阵和向量的转置问题

    numpy有很多方法进行转置,这里由于时间和精力限制(主要是我实在比较懒,有一个基本上一直能使的,就懒得看其他的了),其他方法我没研究,这里我总结的东西,如果有问题,欢迎各路大佬拍砖 一.创建矩阵: ...