跳過到頁腳內容
.NET HELP

Microsoft Logging C# (How It Works For Developers)

日誌記錄是 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:將日誌記錄器介面注入到控制台

若要使用日誌記錄功能,您需要將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>();
$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
});
$vbLabelText   $csharpLabel

步驟 5:編寫不同等級的日誌

現在可以使用 logger 物件寫入不同等級的日誌。 可用的日誌記錄方法有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");
$vbLabelText   $csharpLabel

步驟 6:運行程式碼

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

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

安裝 MS Logging

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

  1. 啟動 Visual Studio。
  2. 導覽至"工具">"NuGet 套件管理器">"套件管理器控制台"
  3. 在軟體包管理器控制台中,執行下列命令:

    Install-Package Microsoft.Extensions.Logging
  4. Enter 鍵執行指令。 這將下載Microsoft.Extensions.Logging套件並將其安裝到您的專案中。

日誌等級

Microsoft.Extensions.Logging框架在 C# 中提供了多個日誌級別,使開發人員能夠根據日誌訊息的重要性和嚴重性對其進行分類和排序。 這些等級通常用於區分各種訊息類型,並有助於控制日誌的詳細程度。

Microsoft.Extensions.Logging提供的預設日誌等級如下:

*追蹤:*最徹底的級別,通常用於極其詳細的數據,可以深入了解程式的內部運作。 調試資訊:在開發和調試階段很有用的調試信息,但在生產環境中通常不需要。 資訊:提供有關應用程式正常運作方式的詳細資訊。 通常情況下,程式的正常運作情況會透過這些日誌進行監控。 警告:指出可能存在的問題或將來可能需要注意的事項。 它用於處理可能導致問題但不一定會導致程式崩潰的異常或意外情況。 錯誤:表示有嚴重問題或錯誤,需要立即修復。 通常用於記錄影響應用程式運行的問題。 嚴重:**最嚴重的狀態,用於記錄需要立即解決的嚴重問題,因為它們可能會導致嚴重問題或程式崩潰。

每個日誌等級都有其特定的用途,並使開發人員能夠管理日誌框架輸出的資料量。 開發人員可以根據記錄資料的嚴重性和重要性選擇合適的訊息記錄等級。

配置 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
    }
}
$vbLabelText   $csharpLabel

在這個例子中,日誌配置中新增了一個控制台日誌記錄器,它會將日誌寫入控制台。 但是, Microsoft.Extensions.Logging提供了各種日誌記錄提供程序,包括將日誌記錄到檔案、資料庫或與其他日誌框架連接。 此外,還可以建立自訂日誌記錄提供程序,根據特定要求格式化日誌。

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

您可以透過在Create()函數中連結相關方法來新增其他日誌來源。 例如:

  • 若要新增偵錯器輸出日誌記錄提供程序,請使用builder.AddDebug()
  • 若要新增檔案日誌記錄提供程序,請使用builder.AddFile(&quot;log.txt&quot;)

在 IronPDF 上進行 MSLogging

IronPDF 在HTML 轉 PDF 方面表現出色,可確保精確保留原始佈局和樣式。 它非常適合從基於 Web 的內容(例如報告、發票和文件)建立 PDF。 IronPDF 支援 HTML 檔案、URL 和原始 HTML 字串,可以輕鬆產生高品質的 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");
    }
}
$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();
    }
}
$vbLabelText   $csharpLabel

在這個範例中,我們建立了Microsoft.Extensions.Logging框架的LoggerFactory實例。 然後我們從工廠為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
    }
}
$vbLabelText   $csharpLabel

本範例示範了在採用 IronPDF 的 C# 應用程式中設定 Microsoft.Extensions.Logging 的簡單方法。 日誌訊息用於記錄 PDF 的成功創建,並記錄可能發生的任何異常情況。

請務必根據應用程式的特定需求以及 IronPDF 用於建立或修改 PDF 的場景,自訂日誌等級、錯誤處理和訊息。 使用日誌等級正確區分不同類型的日誌訊息,對於有效的偵錯和監控非常有用。

要了解更多關於 IronPDF 的信息,請訪問IronPDF 主頁

結論

總之,整合 Microsoft.Extensions.Logging 可以讓 C# 開發人員有效地處理日誌記錄任務。 IronPDF 提供全面的日誌記錄功能,能夠徹底記錄、分析和報告應用程式事件、故障和重要數據。 這提高了應用程式的可靠性、可維護性和調試性。

IronPDF 提供不同的軟體產品,包括售價$799 Lite 套裝。 此套餐包含永久許可證、升級選項、一年軟體維護和 30 天退款保證。 在有浮水印的試用期內,您可以探索 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 提供了追蹤、除錯、資訊、警告、錯誤和關鍵等日誌層級。這些層級可協助開發人員根據嚴重性和重要性來分類日誌訊息。

如何在 .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 的產生過程。開發人員可追蹤應用程式事件、錯誤和效能問題,進而提升可靠性並簡化故障排除。

Jacob Mellor,技術長 @ Team Iron
首席技術長

Jacob Mellor 是 Iron Software 的首席技術長,也是開創 C# PDF 技術的有遠見的工程師。作為 Iron Software 核心程式碼庫背後的原始開發人員,他從公司成立之初就塑造了公司的產品架構,與首席執行官 Cameron Rimington 一起將公司轉型為一家 50 多人的公司,為 NASA、Tesla 和全球政府機構提供服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽工程學士學位 (BEng)(1998-2001 年)。

Jacob 於 1999 年在倫敦開設了他的第一家軟體公司,並於 2005 年創建了他的第一個 .NET 元件,之後,他專門解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF & Iron Suite for .NET 函式庫在全球的 NuGet 安裝量已超過 3000 萬次,他的基礎程式碼持續為全球使用的開發人員工具提供動力。Jacob 擁有 25 年的商業經驗和 41 年的編碼專業知識,他一直專注於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代的技術領導者。