| 房產 | 價值觀 |
|---|---|
| 規則識別碼 | 約1873年 |
| 標題 | 避免可能昂貴的記錄 |
| 類別 | 效能 |
| 修正是破壞性或非破壞性 | Non-breaking |
| 在 .NET 10 中預設啟用 | 建議 |
原因
在許多情況下,記錄會停用或設定為記錄層級,這會導致記錄引數的不必要評估。
規則描述
呼叫記載方法時,無論是否啟用記載層級,都會評估其引數。 這可能會導致即使不會寫入記錄訊息,也會執行昂貴的作業。 為了獲得更好的效能,請檢查或使用LoggerMessage模式來IsEnabled保護昂貴的日誌記錄呼叫。
如何修正違規
若要修正違反此規則的問題,請使用下列其中一種方法:
- 使用檢查來 IsEnabled保護日誌記錄呼叫。
- 將模式
LoggerMessage與 LoggerMessageAttribute一起使用。 - 除非必要,否則請確定不會在記錄引數中執行昂貴的作業。
Example
下列程式碼片段顯示 CA1873 的違規情況:
using Microsoft.Extensions.Logging;
class Example
{
private readonly ILogger _logger;
public Example(ILogger<Example> logger)
{
_logger = logger;
}
public void ProcessData(int[] data)
{
// Violation: expensive operation in logging argument.
_logger.LogDebug($"Processing {string.Join(", ", data)} items");
// Violation: object creation in logging argument.
_logger.LogTrace("Data: {Data}", new { Count = data.Length, Items = data });
}
}
Imports Microsoft.Extensions.Logging
Class Example
Private ReadOnly _logger As ILogger
Public Sub New(logger As ILogger(Of Example))
_logger = logger
End Sub
Public Sub ProcessData(data As Integer())
' Violation: expensive operation in logging argument.
_logger.LogDebug($"Processing {String.Join(", ", data)} items")
' Violation: object creation in logging argument.
_logger.LogTrace("Data: {Data}", New With {.Count = data.Length, .Items = data})
End Sub
End Class
下列程式碼片段修正違規:
using Microsoft.Extensions.Logging;
class Example
{
private readonly ILogger _logger;
public Example(ILogger<Example> logger)
{
_logger = logger;
}
public void ProcessData(int[] data)
{
// Fixed: guard with IsEnabled check.
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug($"Processing {string.Join(", ", data)} items");
}
// Fixed: guard with IsEnabled check.
if (_logger.IsEnabled(LogLevel.Trace))
{
_logger.LogTrace("Data: {Data}", new { Count = data.Length, Items = data });
}
}
}
Imports Microsoft.Extensions.Logging
Class Example
Private ReadOnly _logger As ILogger
Public Sub New(logger As ILogger(Of Example))
_logger = logger
End Sub
Public Sub ProcessData(data As Integer())
' Fixed: guard with IsEnabled check.
If _logger.IsEnabled(LogLevel.Debug) Then
_logger.LogDebug($"Processing {String.Join(", ", data)} items")
End If
' Fixed: guard with IsEnabled check.
If _logger.IsEnabled(LogLevel.Trace) Then
_logger.LogTrace("Data: {Data}", New With {.Count = data.Length, .Items = data})
End If
End Sub
End Class
隱藏警告的時機
如果效能不是問題,或記錄引數不涉及昂貴的作業,則可以安全地隱藏此規則的警告。
隱藏警告
如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。
#pragma warning disable CA1873
// The code that's violating the rule is on this line.
#pragma warning restore CA1873
若要停用檔案、資料夾或項目的規則,請在組態檔
[*.{cs,vb}]
dotnet_diagnostic.CA1873.severity = none
如需詳細資訊,請參閱 如何隱藏程式碼分析警告。