.NET 幫助

Microsoft 日誌記錄 C#(開發者如何運作)

發佈 2024年1月27日
分享:

介紹

記錄是 C# 中一種基本技術,它在應用程式運行時捕捉資訊、警告、錯誤和其他相關數據。它幫助開發者監控程式的行為方式、排除問題,以及理解應用程式在各種情境中的運作方式。C# 提供了一些記錄框架和套件,以簡化記錄工作。 [Microsoft.Extensions.Logging

](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging?view=dotnet-plat-ext-8.0) 是 .NET Core 應用程式中最常用的日誌記錄框架之一。Microsoft.Extensions.Logging NuGet 套件為 .NET Core 提供了多種擴展方法,幫助我們撰寫不同的日誌級別。在本文中,我們將深入了解 MS 日誌記錄。

如何設置 MS Logging

  1. 建立一個新的 Visual Studio 專案。

  2. Microsoft.Extensions.Logging 安裝庫 NuGet.

  3. Logger 介面注入到控制台中。

  4. 配置日誌輸出。

  5. 在不同級別寫入日誌。

  6. 執行代碼。

第一步:創建一個新的 Visual Studio 專案

要開始,請在 Visual Studio 中創建一個新專案。

步驟二:安裝 Microsoft.Extensions.Logging 程式庫

使用以下命令安裝 Microsoft.Extensions.Logging 程式庫 NuGet這個庫為 .NET Core 應用程序提供必要的類和方法來進行日誌記錄。

步驟3:將 Logger 介面注入到控制台

要使用記錄功能,您需要將 Logger 介面的實例注入到您的控制台應用程式中。這可以通過使用依賴注入框架或手動創建 Logger 類的實例來完成。

using Microsoft.Extensions.Logging;

// Inject the logger into the console
ILogger logger = LoggerFactory.Create(builder =>
{
    builder.AddConsole();
}).CreateLogger<Program>();
using Microsoft.Extensions.Logging;

// Inject the logger into the console
ILogger logger = LoggerFactory.Create(builder =>
{
    builder.AddConsole();
}).CreateLogger<Program>();
Imports Microsoft.Extensions.Logging

' Inject the logger into the console
Private logger As ILogger = LoggerFactory.Create(Sub(builder)
	builder.AddConsole()
End Sub).CreateLogger<Program>()
VB   C#

第四步: 配置日誌輸出

配置日誌應該如何輸出。這可以通過向日誌生成器添加一個或多個日誌提供者來完成。最常見的提供者是控制臺日誌記錄器,它將日誌輸出到控制臺。

builder.AddConsole(options =>
{
    options.TimestampFormat = "[HH:mm:ss] ";
});
builder.AddConsole(options =>
{
    options.TimestampFormat = "[HH:mm:ss] ";
});
builder.AddConsole(Sub(options)
	options.TimestampFormat = "[HH:mm:ss] "
End Sub)
VB   C#

步驟 5: 寫入不同層級的日誌紀錄

您現在可以使用 logger 物件在不同層級寫入日誌紀錄。可用的日誌紀錄方法包括 LogDebug(), 日志信息(), 記錄警告(), 記錄錯誤(), 和 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")
VB   C#

第六步:運行代碼

最後,運行你的代碼,並觀察根據已配置的設置輸出的日誌。

就這樣! 您已成功在您的 C# 應用程式中設置並使用了 MS 日誌記錄。

安裝 MS Logging

若要安裝 MS Logging,請按照以下步驟操作:

  1. 啟動 Visual Studio。
  2. 依次導航到 工具 > NuGet 套件管理器 > 套件管理器控制台
  3. 在套件管理器控制台中,執行以下命令:
    Install-Package Microsoft.Extensions.Logging
  1. Enter 執行命令。這將下載並安裝 Microsoft.Extensions.Logging 套件到你的專案中。

日誌級別

在 C# 的 Microsoft.Extensions.Logging 框架中提供了多種日誌級別,允許開發者根據資訊的重要性和嚴重程度分類和排序日誌訊息。這些級別通常用於區分不同類型的訊息,並幫助調節日誌的詳細程度。

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();
    }
}
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();
    }
}
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()
	End Sub
End Class
VB   C#

在此範例中,將控制台記錄器新增到日誌配置中,該記錄器會將日誌寫入控制台。然而,Microsoft.Extensions.Logging 提供各種日誌提供者,包括寫入文件、數據庫,或與其他日誌框架連接。此外,還可以創建自定義的日誌提供者,以根據特定需求來格式化日誌。

包含額外的日誌記錄提供者

您可以通過在 Create 方法中連鎖相關的方法來添加額外的日誌記錄來源()例如:

  • 要添加調試器輸出日誌提供者,請使用 builder.AddDebug().
  • 若要添加文件日志提供程序,请使用 builder.AddFile("log.txt")`.

在 IronPDF 上啟用 MSLogging

要在 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
VB   C#

在此範例中,我們從 Microsoft.Extensions.Logging 框架創建一個 LoggerFactory 實例。接著,我們從工廠為 Program 類別創建一個 logger。

要在 IronPDF 中啟用日誌記錄,我們將靜態 Logger.Log 屬性設置為從 loggerFactory 獲取的 LoggerImplementation 實例。透過這種配置,您可以使用 Logger.Log 方法在 IronPDF 內記錄訊息。

在使用 IronPDF 執行必要的操作後,您可以關閉並處理資源,然後通過處置 loggerFactory 來刷新日誌訊息。

注意:請確保您已安裝 Microsoft.Extensions.Logging 和 IronPDF 的必要依賴項和包。

安裝 IronPDF

要安裝 IronPDF 函式庫,請按照以下步驟操作:

  1. 在 Visual Studio 中打開套件管理器控制台。
  2. 輸入以下命令,以使用 NuGet 安裝 IronPDF 函式庫:
Install-Package IronPdf

或者,您可以在終端中運行以下命令來使用 .NET CLI:

dotnet add package IronPdf
  1. 按下 Enter 鍵執行命令。這將下載並安裝 IronPDF 套件到您的專案中。

也可以使用 NuGet 套件管理器 GUI 安裝 IronPDF 庫。在瀏覽標籤中搜尋 "IronPDF" 套件,從列表中選擇所需的套件,並安裝最新版本的 IronPDF。

安裝完成後,您可以在您的專案中開始使用 IronPDF 庫。

MS Logging using IronPDF

截至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();
    }
}
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();
    }
}
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()
	End Sub
End Class
VB   C#

此範例演示了一種在使用IronPDF的C#應用程式中設置Microsoft.Extensions.Logging的簡單方法。日誌訊息生成用於記錄成功創建PDF以及記錄可能發生的任何異常。

請確保根據您的應用程式的特定需求和使用IronPDF進行PDF創建或修改的場景來自定義日誌級別、錯誤處理和訊息。使用日誌級別正確區分不同類型的日誌訊息對於有效的除錯和監控是非常有用的。

要了解更多關於IronPDF的信息,請訪問官方網站。

結論

總而言之,整合 Microsoft.Extensions.Logging 允許 C# 開發者有效地處理記錄任務。IronPDF 提供全面的記錄功能,能夠徹底記錄、分析和報告應用程式事件、故障和重要資料。這增強了應用程式的可靠性、維護性和除錯能力。

IronPDF 提供不同的軟體產品,包括價格為 $749 的輕量級組合。此組合包括永久許可證、升級選項、一年的軟體維護和三十天的退款保證。在有浮水印的試用期間,您可以探索 IronPDF 的功能。欲了解更多 Iron Software 提供的軟體產品信息,請訪問他們的官方網站。 https://ironsoftware.com/.

< 上一頁
Cefsharp.WPF.NET Core(開發人員如何運作)
下一個 >
Serilog .NET(開發者使用方式)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >