[英]FXCop Custom Rule to detect if catch has logging (Custom Code Analysis)
我已經實現了幾個“常規” Microsoft代碼分析規則。 但是,他們缺乏一個地方,在捕獲中沒有檢測到是否可以實施日志記錄。
所以我的測試項目有這兩種方法。 我希望看到其中一個引發我的自定義錯誤,而另一個通過。
public void CatchTestNoLogging()
{
try
{ string A = "adsf"; }
catch (Exception ex)
{ throw; }
}
public void CatchTestLogging()
{
try
{ string A = "adsf"; }
catch (Exception ex)
{
log.Error("Test Error");
throw;
}
}
我的自定義規則能夠檢測是否有捕獲,但是看不到如何檢測是否使用了日志記錄?
這是自定義規則的SNIP:
if (iList[i].OpCode == OpCode._Catch)
{
isCatchExists = true; //this gets hit as I want
//so the question is what can I do to detect if logging is implemented in the catch?
}
快速訪問我的訪問方式將非常有用。 謝謝
好,
這不是完美的,但這就是我得到的。 我知道/有一個來自Google的框架,該框架介紹如何查找catch塊...嗯,這只是我需要的一半,所以我從那里開始,代碼看起來像這樣:
if (item.OpCode == OpCode._Catch)
{
isCatchExists = true;
}
因此,我逐步進入了調試器,以查看與不進行日志記錄相比,日志記錄(log4net)的捕獲情況如何,並查看是否出現了明顯的問題。 好吧,我確實發現了這一點:
探索log4net對象,我看到以下內容:
因此,我沒有找到確定log.error是否存在的方法,但是我可以確定是否存在該錯誤。 所以我這樣寫:
public override ProblemCollection Check(Member member)
{
Method method = member as Method;
bool isCatchExists = false;
bool isLogError = false;
if(method != null)
{
//Get all the instrections of the method.
InstructionCollection iList = method.Instructions;
foreach (Instruction item in iList)
{
#region Check For Catch
if (item.OpCode == OpCode._Catch)
{
isCatchExists = true;
}
#endregion
#region Check for Error Logging (log4net)
if (item.Value != null)
{
if (item.OpCode == OpCode.Callvirt && item.Value.ToString() == "log4net.ILog.Error")
{
isLogError = true;
}
}
#endregion
}
if (isCatchExists && !isLogError)
{
Problems.Add(new Problem(this.GetNamedResolution("AddLogging", member.FullName)));
}
}
return this.Problems;
}
這有效,但有一些警告。
這是硬編碼到log4net。 一種。 我不喜歡硬代碼,但無論如何我可能會為其他日志記錄方法添加一條不同的規則。
我無法確定log.error是否在catch塊中。 一種。 因此,一個人可能在try塊中遇到log.error,而我的規則將通過它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.