如何在 C# 中使用自定義日誌
自訂日誌記錄是指根據應用程式或系統的特定需求和要求實施日誌記錄系統的做法。 涉及創建和使用日誌文件來記錄軟件在運行期間產生的信息、事件和消息。
開始使用 IronPDF
立即在您的專案中使用IronPDF,並享受免費試用。
如何在 C# 中使用自定义日志记录
- 從 NuGet 下載 IronPDF
- 將 LoggingMode 屬性設置為 LoggingModes.Custom
- 將CustomLogger屬性分配給您的自定義日誌物件
- 所有日誌消息將會轉發到自定義記錄器
- 輸出日誌信息以查看日誌
自訂記錄範例
要使用自訂記錄功能,請將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");
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}");
}
}
在這種情況下,我在日誌訊息前添加了額外的信息。
