🎈个人主页:靓仔很忙i
💻B 站主页:👉B站👈
🎉欢迎 👍点赞✍评论⭐收藏
🤗收录专栏:C#
🤝希望本文对您有所裨益,如有不足之处,欢迎在评论区提出指正,让我们共同学习、交流进步!
需求
:对于不方便debug的程序,查看日志是一个特别好的调试方式,但是在.net framework中,想实现面向切面打印日志特别困难。有人可能会想到使用Castle,使用Castle确实ok。但它需要依赖注入,需要框架去托管所有需要AOP的对象,系统中还有很多静态类,想实现这些都类的日志打印,我还需要去包装类库中的所有的静态类。这显然不现实,本文就是为了解决这个问题而写。
解决方案:
为此,笔者写了一个Logger类,提供了CallStatic,CallMethod方式分别去调用方法,调用方法的时候,打印日志。调用思路也很简单,直接调用就行,需要调用的方法,通过参数传递即可。废话不多说,直接上干货。
- 程序需要三个文件
- Logger:日志类
- MyService: 测试使用的方法
- Program: 入口
- Logger文件
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace AutoTemplate.log
{
public static class Logger
{
public static void CallStatic(Expression<Action> expression)
{
var methodInfo = (MethodCallExpression)expression.Body;
var method = GetMethodInfo(methodInfo);
var parameters = GetParameters(methodInfo);
PrintStartLog(method, parameters);
method.Invoke(null, parameters);
PrintEndLog(method);
}
public static T CallStatic<T>(Expression<Func<T>> expression)
{
var methodInfo = (MethodCallExpression)expression.Body;
var method = GetMethodInfo(methodInfo);
var parameters = GetParameters(methodInfo);
PrintStartLog(method, parameters);
var result = (T)method.Invoke(null, parameters);
PrintEndLog(method);
return result;