1
我正在使用OnMethodBoundryAspect創建簡單的日誌記錄和執行時間方面。我想爲每種方法創建一個記錄器。但是,如果Logger未聲明爲靜態成員,則不起作用。如果聲明爲靜態,則不可能爲每個方法創建一個記錄器。PostSharp和Common.Logging 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
}
感謝全面的回答!但是,您的StopWatch方法會產生不正確的時間。我有一個方法,其中我使用Thread.Sleep(2000),但秒錶返回1991.使用我的代碼,它返回2001. –
這是一個奇怪的行爲,在我的測試中,我通常會得到2001-2002毫秒結果與相同的代碼。或者,您也可以嘗試將秒錶實例存儲在標籤中:'args.MethodExecutionTag = Stopwatch.StartNew()'。 – AlexD