1.Install Nlog
進入NuGet,安裝下面的包
2. Config
3.Aspect
3.1 Install Aspect
進入NuGet,安裝下面的包MethodBoundaryAspect.Fody
3.2 Create Aspect cs
using MethodBoundaryAspect.Fody.Attributes;
using System;
using System.Diagnostics;
namespace xxxxx.Extension.Aspect
{
[Serializable]
public class LoggingAspect : OnMethodBoundaryAspect
{
private Stopwatch stopwatch = new Stopwatch();
private string router;
public string Router
{
get { return router; }
set { router = value; }
}
public override void OnEntry(MethodExecutionArgs args)
{
if (stopwatch.IsRunning)
{
stopwatch.Stop();
}
stopwatch.Start();
}
public override void OnExit(MethodExecutionArgs args)
{
stopwatch.Stop();
// 获取方法执行时间(毫秒)
double elapsedTime = stopwatch.ElapsedMilliseconds;
//獲取router,根據自己的情況將api請求路徑放入router
xxxxxx
System.Diagnostics.Trace.WriteLine("Service: "+serviceName+",Method: "+Router+",Execution time: " + elapsedTime + "ms.");
}
}
}
3.3 Use
將注釋放入到Service的每一個方法上,就可以了
public interface IMyService
{
void DoSomething();
}
[Serializable]
public class MyService : IMyService
{
[LoggingAspect] // 应用切面到该方法上
public void DoSomething()
{
// 执行一些操作...
}
}