我正在使用 OnMethodBoundryAspect 创建一个简单的日志记录和执行时间方面。我想为每个方法创建一个记录器。但是,如果 Logger 未声明为静态成员,则它不起作用。如果将其声明为静态,则不可能为每个方法创建一个记录器。
这是我的方面:
[Serializable]
public class MonitorAttribute : OnMethodBoundaryAspect
{
[NonSerialized]
private Stopwatch _stopwatch;
private string _methodName;
private ILog _log;
public MonitorAttribute()
{
}
/// <summary>
/// overrides the method name in the logs
/// </summary>
/// <param name="method"></param>
public MonitorAttribute(string method)
{
_methodName = method;
}
#region Overrides
public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo)
{
if (string.IsNullOrEmpty(_methodName))
_methodName = method.Name;
_log = LogManager.GetLogger(_methodName);
}
public override void OnEntry(MethodExecutionArgs args)
{
_stopwatch = Stopwatch.StartNew();
_log.InfoFormat("Method {0} called", _methodName);
}
public override void OnExit(MethodExecutionArgs args)
{
_stopwatch.Stop();
_log.InfoFormat("Method {0} exited successfully. execution time {1} milliseconds", _methodName, _stopwatch.ElapsedMilliseconds);
}
public override void OnSuccess(MethodExecutionArgs args)
{
_stopwatch.Stop();
_log.InfoFormat("Method {0} executed successfully. execution time {1} milliseconds", _methodName, _stopwatch.ElapsedMilliseconds);
}
#endregion
}