跳至页脚内容
.NET 帮助

Microsoft Logging C#(开发者如何使用)

日志记录是C#中捕获信息、警告、错误和其他相关数据的基本技术,同时应用程序正在运行。 它帮助开发人员监控程序的行为,排除故障,并了解应用程序在不同环境中的功能。 C#提供了一些日志框架和包,以简化日志任务。 Microsoft.Extensions.Logging 是 .NET Core 应用程序中最广泛使用的日志框架之一。 用于 .NET Core 的 Microsoft.Extensions.Logging NuGet 包为我们提供了几个扩展方法,以帮助我们编写不同的日志级别。 在本文中,我们将更多地了解 MS 日志记录。

如何设置 MS 日志记录

  1. 创建一个新的 Visual Studio 项目。
  2. NuGet 上的 Microsoft.Extensions.Logging 包页面 安装 Microsoft.Extensions.Logging 库。
  3. Logger 接口注入控制台。
  4. 配置日志输出。
  5. 在不同级别写入日志。
  6. 运行代码。

步骤 1:创建一个新的 Visual Studio 项目

要开始,请在 Visual Studio 中创建一个新项目。

步骤 2:安装 Microsoft.Extensions.Logging 库

使用 NuGet 上的 Microsoft.Extensions.Logging 包页面 安装 Microsoft.Extensions.Logging 库。 此库为 .NET Core 应用程序的日志记录提供必要的类和方法。

步骤 3:将 Logger 接口注入控制台

要使用日志功能,需要将 ILogger 接口的实例注入到控制台应用程序中。 这可以通过使用日志工厂来完成。

using Microsoft.Extensions.Logging;

// Create a logger for the application
ILogger<Program> logger = LoggerFactory.Create(builder =>
{
    builder.AddConsole(); // Adding console logging
}).CreateLogger<Program>();
using Microsoft.Extensions.Logging;

// Create a logger for the application
ILogger<Program> logger = LoggerFactory.Create(builder =>
{
    builder.AddConsole(); // Adding console logging
}).CreateLogger<Program>();
Imports Microsoft.Extensions.Logging

' Create a logger for the application
Private logger As ILogger(Of Program) = LoggerFactory.Create(Sub(builder)
	builder.AddConsole() ' Adding console logging
End Sub).CreateLogger<Program>()
$vbLabelText   $csharpLabel

步骤 4:配置日志输出

配置日志的输出方式。 这可以通过向日志记录器生成器添加一个或多个日志提供程序来实现。 最常见的提供者是控制台日志记录器,它将日志输出到控制台。

builder.AddConsole(options =>
{
    options.TimestampFormat = "[HH:mm:ss] "; // Setting the timestamp format for logs
});
builder.AddConsole(options =>
{
    options.TimestampFormat = "[HH:mm:ss] "; // Setting the timestamp format for logs
});
builder.AddConsole(Sub(options)
	options.TimestampFormat = "[HH:mm:ss] " ' Setting the timestamp format for logs
End Sub)
$vbLabelText   $csharpLabel

步骤 5:在不同级别写入日志

现在可以使用日志记录器对象在不同级别写入日志。 可用的日志记录方法有 LogDebug()LogInformation()LogWarning()LogError()LogCritical()

logger.LogDebug("This is a debug message");
logger.LogInformation("This is an information message");
logger.LogWarning("This is a warning message");
logger.LogError("This is an error message");
logger.LogCritical("This is a critical message");
logger.LogDebug("This is a debug message");
logger.LogInformation("This is an information message");
logger.LogWarning("This is a warning message");
logger.LogError("This is an error message");
logger.LogCritical("This is a critical message");
logger.LogDebug("This is a debug message")
logger.LogInformation("This is an information message")
logger.LogWarning("This is a warning message")
logger.LogError("This is an error message")
logger.LogCritical("This is a critical message")
$vbLabelText   $csharpLabel

步骤 6:运行代码

最后,运行您的代码,并根据配置的设置观察日志输出。

就是这样! 您已成功在 C# 应用程序中设置并使用 MS 日志记录。

安装 MS 日志记录

要安装 MS 日志记录,请按照以下步骤操作:

  1. 启动 Visual Studio。
  2. 导航到 工具 > NuGet 包管理器 > 包管理器控制台
  3. 在包管理器控制台中执行以下命令:

    Install-Package Microsoft.Extensions.Logging
  4. Enter 键执行命令。 这将下载并安装 Microsoft.Extensions.Logging 包到您的项目中。

日志级别

Microsoft.Extensions.Logging 框架在 C# 中提供了几个日志级别,使开发人员能够根据重要性和严重性对日志消息进行分类和排序。 这些级别通常用于区分不同类型的消息,帮助调节日志的详细程度。

Microsoft.Extensions.Logging 提供的默认日志级别如下:

  • Trace:最详细的级别,通常用于提供非常详细的数据,以深入了解程序的内部工作。
  • Debug:调试信息,在开发和调试阶段有用,但通常不在生产环境中使用。
  • Information:提供有关应用程序正常运作的详细信息。 通常,这些日志用于监控程序的正常操作。
  • Warning:指出可能的问题或将来可能需要关注的任何事情。 用于记录异常或意外情况,这些情况可能导致问题,但不一定会导致程序崩溃。
  • Error:表示需要立即修复的严重问题或错误。 通常用于记录影响应用程序操作的问题。
  • Critical:最严重的状态,用于记录需要立即解决的关键问题,因为它们可能导致严重问题或程序崩溃。

每个日志级别都有其特定用途,能够让开发人员管理日志框架输出的数据量。 开发人员可以根据记录数据的严重性和重要性选择合适的级别进行消息记录。

配置 C# 日志记录

以下是如何使用 Microsoft.Extensions.Logging 配置日志记录的基本示例:

using Microsoft.Extensions.Logging;
using System;

class Program
{
    // Create a LoggerFactory instance
    private static readonly ILoggerFactory LoggerFactory = LoggerFactory.Create(builder =>
    {
        // Add console logger
        builder.AddConsole();
        // You can add other logging providers here (e.g., AddDebug, AddFile, etc.)
    });

    // Create a logger
    private static readonly ILogger Logger = LoggerFactory.CreateLogger<Program>();

    static void Main(string[] args)
    {
        // Example log messages
        Logger.LogInformation("Information log");
        Logger.LogWarning("Warning log");
        Logger.LogError("Error log");

        try
        {
            // Simulate an exception
            throw new Exception("Exception occurred");
        }
        catch (Exception ex)
        {
            // Log exception details
            Logger.LogError(ex, "Exception log");
        }

        Console.ReadKey(); // Wait for a key press before closing the application
    }
}
using Microsoft.Extensions.Logging;
using System;

class Program
{
    // Create a LoggerFactory instance
    private static readonly ILoggerFactory LoggerFactory = LoggerFactory.Create(builder =>
    {
        // Add console logger
        builder.AddConsole();
        // You can add other logging providers here (e.g., AddDebug, AddFile, etc.)
    });

    // Create a logger
    private static readonly ILogger Logger = LoggerFactory.CreateLogger<Program>();

    static void Main(string[] args)
    {
        // Example log messages
        Logger.LogInformation("Information log");
        Logger.LogWarning("Warning log");
        Logger.LogError("Error log");

        try
        {
            // Simulate an exception
            throw new Exception("Exception occurred");
        }
        catch (Exception ex)
        {
            // Log exception details
            Logger.LogError(ex, "Exception log");
        }

        Console.ReadKey(); // Wait for a key press before closing the application
    }
}
Imports Microsoft.Extensions.Logging
Imports System

Friend Class Program
	' Create a LoggerFactory instance
	Private Shared ReadOnly LoggerFactory As ILoggerFactory = LoggerFactory.Create(Sub(builder)
		' Add console logger
		builder.AddConsole()
		' You can add other logging providers here (e.g., AddDebug, AddFile, etc.)
	End Sub)

	' Create a logger
	Private Shared ReadOnly Logger As ILogger = LoggerFactory.CreateLogger(Of Program)()

	Shared Sub Main(ByVal args() As String)
		' Example log messages
		Logger.LogInformation("Information log")
		Logger.LogWarning("Warning log")
		Logger.LogError("Error log")

		Try
			' Simulate an exception
			Throw New Exception("Exception occurred")
		Catch ex As Exception
			' Log exception details
			Logger.LogError(ex, "Exception log")
		End Try

		Console.ReadKey() ' Wait for a key press before closing the application
	End Sub
End Class
$vbLabelText   $csharpLabel

在此示例中,将控制台日志记录器添加到日志配置中,以将日志写入控制台。 然而,Microsoft.Extensions.Logging 提供了各种日志提供程序,包括日志记录到文件、数据库,或与其他日志框架连接。 此外,可以创建自定义的日志提供程序,以根据特定要求格式化日志。

包括额外的日志提供程序

可以通过在 Create() 函数中链接相关方法来添加额外的日志来源。 例如:

  • 要添加调试输出日志记录提供程序,使用 builder.AddDebug()
  • 要添加文件日志记录提供程序,使用 builder.AddFile("log.txt")

在 IronPDF 上进行 MSLogging

IronPDF 擅长 HTML 到 PDF 的转换,确保准确保存原始布局和样式。 它非常适合从基于Web的内容中创建PDF,如报告、发票和文档。 利用对HTML文件、URL和原始HTML字符串的支持,IronPDF轻松生成高质量的PDF文档。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

要在 IronPDF 中启用日志记录,可以使用 Microsoft.Extensions.Logging 框架,以及 IronPDF 内置的日志记录功能。 以下是如何在 IronPDF 中设置日志记录的示例:

using Microsoft.Extensions.Logging;
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
        {
            builder
                .AddConsole()
                .AddDebug();
        });

        ILogger<Program> logger = loggerFactory.CreateLogger<Program>();

        // Enable logging in IronPDF
        Logger.Log = new LoggerImplementation(logger);

        // Use IronPDF and perform operations
        // ...

        // Example of logging an error in IronPDF
        Logger.Log.Error("An error occurred while processing the PDF");

        // Example of logging a warning in IronPDF
        Logger.Log.Warning("This is a warning message");

        // Example of logging an information message in IronPDF
        Logger.Log.Information("This is an information message");

        // ...

        // Close and dispose resources
        // ...

        // Flush the log messages
        loggerFactory.Dispose();
    }
}
using Microsoft.Extensions.Logging;
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
        {
            builder
                .AddConsole()
                .AddDebug();
        });

        ILogger<Program> logger = loggerFactory.CreateLogger<Program>();

        // Enable logging in IronPDF
        Logger.Log = new LoggerImplementation(logger);

        // Use IronPDF and perform operations
        // ...

        // Example of logging an error in IronPDF
        Logger.Log.Error("An error occurred while processing the PDF");

        // Example of logging a warning in IronPDF
        Logger.Log.Warning("This is a warning message");

        // Example of logging an information message in IronPDF
        Logger.Log.Information("This is an information message");

        // ...

        // Close and dispose resources
        // ...

        // Flush the log messages
        loggerFactory.Dispose();
    }
}
Imports Microsoft.Extensions.Logging
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim loggerFactory As ILoggerFactory = LoggerFactory.Create(Sub(builder)
			builder.AddConsole().AddDebug()
		End Sub)

		Dim logger As ILogger(Of Program) = loggerFactory.CreateLogger(Of Program)()

		' Enable logging in IronPDF
		Logger.Log = New LoggerImplementation(logger)

		' Use IronPDF and perform operations
		' ...

		' Example of logging an error in IronPDF
		Logger.Log.Error("An error occurred while processing the PDF")

		' Example of logging a warning in IronPDF
		Logger.Log.Warning("This is a warning message")

		' Example of logging an information message in IronPDF
		Logger.Log.Information("This is an information message")

		' ...

		' Close and dispose resources
		' ...

		' Flush the log messages
		loggerFactory.Dispose()
	End Sub
End Class
$vbLabelText   $csharpLabel

在此示例中,我们创建了一个 LoggerFactory 实例,来自 Microsoft.Extensions.Logging 框架。 然后,我们从工厂为 Program 类创建了一个日志记录器。

为了在 IronPDF 中启用日志记录,我们将静态 Logger.Log 属性设置为 LoggerImplementation 实例,该实例从 loggerFactory 获取日志记录器。 通过这种配置,可以使用 Logger.Log 方法在 IronPDF 中记录消息。

在完成 IronPDF 所需的操作后,可以关闭和处置资源,然后通过处置 loggerFactory 来刷新日志消息。

注意:确保为 Microsoft.Extensions.Logging 和 IronPDF 安装了必要的依赖项和包。

安装IronPDF

要安装 IronPDF 库,请按照以下步骤操作:

  1. 在 Visual Studio 中打开包管理器控制台。
  2. 输入以下命令,通过 NuGet 安装 IronPDF 库:
Install-Package IronPdf

或者,可以通过在终端中运行以下命令使用 .NET CLI:

Install-Package IronPdf
  1. Enter 键执行命令。 这将下载并安装 IronPDF 包到您的项目中。

还可以通过使用 NuGet 包管理器 GUI 安装 IronPDF 库。 只需在浏览选项卡中搜索 "IronPDF" 包,从列表中选择所需的包,并安装 IronPDF 的最新版本。

安装完成后,您可以在项目中开始使用 IronPDF 库。

使用 IronPDF 进行 MS 日志记录

截至 2022 年 1 月,IronPDF 不直接与 Microsoft.Extensions.Logging 交互,且未提供原生支持。 IronPDF 主要用作在 C# 程序中创建和修改 PDF 的工具。

然而,您仍然可以使用 Microsoft.Extensions 进行日志记录。 通过在 C# 程序中与 IronPDF 一起集成日志记录,可以管理和记录与 PDF 生成、应用程序工作流相关的事件,或在使用 IronPDF 时发生的问题。

以下是如何使用 Microsoft.Extensions 与 IronPDF 集成日志记录的示例:

using Microsoft.Extensions.Logging;
using IronPdf;
using System;

class Program
{
    private static readonly ILoggerFactory LoggerFactory = LoggerFactory.Create(builder =>
    {
        builder.AddConsole(); // Add other logging providers as needed
    });

    private static readonly ILogger Logger = LoggerFactory.CreateLogger<Program>();

    static void Main(string[] args)
    {
        try
        {
            // Your IronPDF code for PDF generation or manipulation
            var Renderer = new IronPdf.HtmlToPdf();
            var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");
            PDF.SaveAs("Output.pdf");
            Logger.LogInformation("PDF created successfully.");
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "An error occurred while generating the PDF.");
        }

        Console.ReadKey(); // Wait for a key press before closing the application
    }
}
using Microsoft.Extensions.Logging;
using IronPdf;
using System;

class Program
{
    private static readonly ILoggerFactory LoggerFactory = LoggerFactory.Create(builder =>
    {
        builder.AddConsole(); // Add other logging providers as needed
    });

    private static readonly ILogger Logger = LoggerFactory.CreateLogger<Program>();

    static void Main(string[] args)
    {
        try
        {
            // Your IronPDF code for PDF generation or manipulation
            var Renderer = new IronPdf.HtmlToPdf();
            var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");
            PDF.SaveAs("Output.pdf");
            Logger.LogInformation("PDF created successfully.");
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "An error occurred while generating the PDF.");
        }

        Console.ReadKey(); // Wait for a key press before closing the application
    }
}
Imports Microsoft.Extensions.Logging
Imports IronPdf
Imports System

Friend Class Program
	Private Shared ReadOnly LoggerFactory As ILoggerFactory = LoggerFactory.Create(Sub(builder)
		builder.AddConsole() ' Add other logging providers as needed
	End Sub)

	Private Shared ReadOnly Logger As ILogger = LoggerFactory.CreateLogger(Of Program)()

	Shared Sub Main(ByVal args() As String)
		Try
			' Your IronPDF code for PDF generation or manipulation
			Dim Renderer = New IronPdf.HtmlToPdf()
			Dim PDF = Renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")
			PDF.SaveAs("Output.pdf")
			Logger.LogInformation("PDF created successfully.")
		Catch ex As Exception
			Logger.LogError(ex, "An error occurred while generating the PDF.")
		End Try

		Console.ReadKey() ' Wait for a key press before closing the application
	End Sub
End Class
$vbLabelText   $csharpLabel

该示例演示了一种简单的方法,在使用 IronPDF 的 C# 应用程序中设置 Microsoft.Extensions.Logging。 生成日志消息以记录 PDF 的成功创建,并记录可能发生的异常。

请确保根据应用程序的具体需求,以及使用 IronPDF 创建或修改 PDF 的场景,自定义日志级别、错误处理和消息。 通过不同日志级别区分不同类型的日志消息,对于有效的调试和监控会非常有用。

要了解有关 IronPDF 的更多信息,请访问 IronPDF 首页。

结论

总之,集成 Microsoft.Extensions.Logging 使 C# 开发人员能够有效地处理日志记录任务。 IronPDF 提供全面的日志记录功能,能够彻底记录、分析和报告应用程序事件、故障和重要数据。 这提升了应用程序的可靠性、维护性和调试能力。

IronPDF 提供了不同的软件产品,包括价格为 $799 的 Lite 捆绑包。 该捆绑包包含永久许可证、升级选项、一年的软件维护,以及三十天的退款保证。 在有水印的试用期内,您可以探索 IronPDF 的功能。 要了解更多关于 Iron Software 提供的软件产品的信息,请访问 Iron Software 的官方网站

常见问题解答

我如何在 .NET Core 应用程序中设置 Microsoft.Extensions.Logging?

要在 .NET Core 应用程序中设置 Microsoft.Extensions.Logging,您需要创建一个新的 Visual Studio 项目,通过 NuGet 安装 Microsoft.Extensions.Logging 包,将 ILogger 接口注入到您的应用程序中,并使用各种提供程序配置您的日志输出。您还可以通过与 IronPDF 集成来增强在 HTML 到 PDF 转换期间的功能。

Microsoft.Extensions.Logging 中有哪些不同的日志级别?

Microsoft.Extensions.Logging 提供了 Trace、Debug、Information、Warning、Error 和 Critical 等日志级别。这些级别有助于开发人员根据严重性和重要性对日志消息进行分类。

如何在 .NET Core 应用程序中注入 ILogger 接口?

在 .NET Core 应用程序中,您可以通过使用依赖注入来注入 ILogger 接口。这涉及在 Startup 类中配置服务容器以包含日志服务,然后将 ILogger 注入到需要日志记录的类中,其中 T 是类的类型。

IronPDF 可以与 Microsoft.Extensions.Logging 框架一起工作吗?

是的,IronPDF 可以与 Microsoft.Extensions.Logging 集成。通过设置一个记录器,您可以使用 IronPDF 的内置功能以及日志记录功能来跟踪和管理应用程序事件和在 PDF 生成期间的问题。

如何为 Microsoft.Extensions.Logging 配置日志输出?

您可以通过将日志提供程序添加到记录器构建器来配置日志输出。例如,使用 builder.AddConsole() 配置控制台输出,并可以使用 builder.AddDebug()builder.AddFile() 将日志定向到其他目的地。

在应用程序开发中的日志记录的目的是什么?

应用程序开发中的日志记录有助于监控应用程序行为、诊断问题并在不同环境中了解应用程序的功能。对于调试和维护应用程序的可靠性尤为重要,尤其是当集成 IronPDF 等工具以执行 HTML 到 PDF 转换等特定任务时。

使用 C# 将 HTML 转换为 PDF 的步骤是什么?

要使用 C# 将 HTML 转换为 PDF,您可以使用 IronPDF。首先,通过 NuGet 确保安装了 IronPDF。然后,使用 IronPDF 的 API 方法如 RenderHtmlAsPdf 将 HTML 字符串或文件转换为 PDF,同时利用日志记录来监控过程。

在项目中将日志记录与 IronPDF 集成的好处是什么?

在项目中将日志记录与 IronPDF 集成可以更好地监控和调试 PDF 生成过程。开发人员可以跟踪应用程序事件、错误和性能问题,从而提高可靠性并简化故障排除。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。