如何在 C&num 中使用自定义日志;
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#
在这种情况下,我在日志信息前添加了附加信息。