如何在 C# 中使用自定義日誌
This article was translated from English: Does it need improvement?
TranslatedView the article in English
自訂日誌記錄是指根據應用程式或系統的特定需求和要求實施日誌記錄系統的做法。 涉及創建和使用日誌文件來記錄軟件在運行期間產生的信息、事件和消息。
開始使用 IronPDF
立即在您的專案中使用IronPDF,並享受免費試用。
如何在 C# 中使用自定义日志记录
- 從NuGet下載IronPDF
- 設置 日誌模式 將屬性設置為 LoggingModes.Custom
- 分配給 自定義記錄器 设置到您自定义的日志记录对象的属性
- 所有日誌消息將會轉發到自定義記錄器
- 輸出日誌信息以查看日誌
自訂記錄範例
要使用自訂日誌功能,請將LoggingMode屬性更改為LoggingModes.Custom。 之後,將CustomLogger屬性指派給您創建的自定義記錄器類。
:path=/static-assets/pdf/content-code-examples/how-to/custom-logging-custom-logging.cs
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.Custom;
IronSoftware.Logger.CustomLogger = new CustomLoggerClass("logging");
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.Custom
IronSoftware.Logger.CustomLogger = New CustomLoggerClass("logging")
VB C#
IronPdf 日誌將被導向到自定義日誌記錄物件。 訊息將與 IronPdf 日誌記錄器中的訊息保持一致; 它們將被直接傳送到自訂的記錄器。 自訂記錄器設計師將決定自訂記錄器如何管理消息。 讓我們使用以下的自定義日誌記錄類作為示例。
:path=/static-assets/pdf/content-code-examples/how-to/custom-logging-custom-logging-class.cs
public class CustomLoggerClass : ILogger
{
private readonly string categoryName;
public CustomLoggerClass(string categoryName)
{
this.categoryName = categoryName;
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
// Implement your custom logging logic here.
string logMessage = formatter(state, exception);
// You can use 'logLevel', 'eventId', 'categoryName', and 'logMessage' to log the message as needed.
// For example, you can write it to a file, console, or another destination.
// Example: Writing to the console
Console.WriteLine($"[{logLevel}] [{categoryName}] - {logMessage}");
}
}
Public Class CustomLoggerClass
Implements ILogger
Private ReadOnly categoryName As String
Public Sub New(ByVal categoryName As String)
Me.categoryName = categoryName
End Sub
Public Function BeginScope(Of TState)(ByVal state As TState) As IDisposable
Return Nothing
End Function
Public Function IsEnabled(ByVal logLevel As LogLevel) As Boolean
Return True
End Function
Public Sub Log(Of TState)(ByVal logLevel As LogLevel, ByVal eventId As EventId, ByVal state As TState, ByVal exception As Exception, ByVal formatter As Func(Of TState, Exception, String))
If Not IsEnabled(logLevel) Then
Return
End If
' Implement your custom logging logic here.
Dim logMessage As String = formatter(state, exception)
' You can use 'logLevel', 'eventId', 'categoryName', and 'logMessage' to log the message as needed.
' For example, you can write it to a file, console, or another destination.
' Example: Writing to the console
Console.WriteLine($"[{logLevel}] [{categoryName}] - {logMessage}")
End Sub
End Class
VB C#
在這種情況下,我在日誌訊息前添加了額外的信息。
