跳過到頁腳內容
.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:將日誌記錄器介面注入到控制台

若要使用日誌記錄功能,您需要將 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 物件寫入不同等級的日誌。 可用的日誌記錄方法有 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 套件到您的專案中。

日誌等級

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

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("log.txt")

在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 提供 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 生成過程。開發者可以跟蹤應用程式事件、錯誤和性能問題,從而提高可靠性並簡化故障排除。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me