如何在 C&num 中使用自定义日志;

Chaknith related to 如何在 C&num 中使用自定义日志;
查克尼特·宾
2023年十一月6日
更新 2025年二月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 票据,还支持产品开发、文档编写和市场营销,从而提升客户的整体体验。当他不在办公室时,他可能会在学习机器学习、编程或徒步旅行。