如何在 C# 中使用自定義日誌
自定义日志记录指的是建立一个日志系统,以满足应用程序或系统的特定需求和要求。它包括创建和使用日志文件来记录由软件在运行过程中生成的信息、事件和消息。
如何在 C# 中使用自定义日志记录
- 下載C#自定義日誌記錄庫
- 設置 日誌模式 property to 日誌模式s.Custom
- 分配給 自定義記錄器 设置到您自定义的日志记录对象的属性
- 所有日誌消息將會轉發到自定義記錄器
- 輸出日誌信息以查看日誌
立即開始在您的專案中使用IronPDF,並享受免費試用。
查看 IronPDF 上 Nuget 快速安裝和部署。已被下載超過800萬次,它正用C#改變PDF。
Install-Package IronPdf
請考慮安裝 IronPDF DLL 直接下載並手動安裝到您的專案或GAC表單: IronPdf.zip
手動安裝到您的項目中
下載DLL自訂日誌範例
要使用自訂日誌功能,將 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")
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
在這種情況下,我在日誌訊息前添加了額外的信息。