如何在 C# 中使用自定義日誌

Chaknith related to 如何在 C# 中使用自定義日誌
查克尼思·賓
2023年11月6日
已更新 2025年2月19日
分享:
This article was translated from English: Does it need improvement?
Translated
View the article in English

自訂日誌記錄是指根據應用程式或系統的特定需求和要求實施日誌記錄系統的做法。 涉及創建和使用日誌文件來記錄軟件在運行期間產生的信息、事件和消息。

開始使用 IronPDF

立即在您的專案中使用IronPDF,並享受免費試用。

第一步:
green arrow pointer



自訂記錄範例

要使用自訂記錄功能,請將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}");
    }
}

在這種情況下,我在日誌訊息前添加了額外的信息。

控制台視窗
Chaknith related to 自訂記錄範例
軟體工程師
Chaknith 是開發者界的夏洛克福爾摩斯。他第一次意識到自己可能有個軟體工程的未來,是在他為了娛樂而參加程式挑戰的時候。他的重點是 IronXL 和 IronBarcode,但他也引以為豪的是,他幫助客戶解決所有產品的問題。Chaknith 利用他與客戶直接對話中獲得的知識,以進一步改進產品。他的實際反饋超越了 Jira 工單,並支持產品開發、文件撰寫和行銷,以提升客戶的整體體驗。不在公司時,他通常在學習機器學習、寫程式和徒步旅行。