.NET幫助 Microsoft Logging C#(開發者的工作原理) Curtis Chau 更新日期:6月 22, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 日誌記錄是 C# 中的一項基本技術,在應用程式運行時捕獲資訊、警告、錯誤和其他相關數據。 它幫助開發人員監控其程式的運行情況、排查問題,以及了解應用如何在不同環境下運行。 C# 提供了一些日誌記錄框架和包,讓記錄工作變得更容易。 Microsoft.Extensions.Logging 是 .NET Core 應用程式中最常用的日誌記錄框架之一。 .NET Core 的 Microsoft.Extensions.Logging NuGet 包為我們提供了多個擴展方法來幫助我們撰寫不同級別的日誌。 在本文中,我們將深入了解 MS 日誌記錄。 如何設置 MS 日誌記錄 創建一個新的 Visual Studio 專案。 從 NuGet 上的 Microsoft.Extensions.Logging 包頁面 安裝 Microsoft.Extensions.Logging 庫。 將 Logger 介面注入到控制台中。 配置日誌輸出。 在不同的級別寫入日誌。 運行代碼。 步驟 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 日誌記錄,請按照以下步驟操作: 啟動 Visual Studio。 導航到 工具 > NuGet 包管理器 > 包管理器控制台。 在包管理器控制台中執行以下命令: Install-Package Microsoft.Extensions.Logging 按 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(); // 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")。 MSLogging 在 IronPDF IronPDF 精通HTML 到 PDF的轉換,確保準確保留原始的佈局和樣式。 它非常適合從網路內容生成 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 在此範例中,我們使用 Microsoft.Extensions.Logging 框架創建 LoggerFactory 的實例。 然後我們從工廠創建了一個用於 程序 類的日誌器。 要在 IronPDF 中啟用日誌記錄,我們將靜態的 Logger.Log 屬性設置為從 loggerFactory 獲取日誌器的 LoggerImplementation 實例。 通過此配置,您可以使用 Logger.Log 方法在 IronPDF 中記錄消息。 在使用 IronPDF 執行必要操作後,您可以關閉並處理資源,然後通過處理 loggerFactory 來刷新日誌消息。 注意:確保已安裝 Microsoft.Extensions.Logging 和 IronPDF 的必要依賴項和套件。 首先,確保你的項目安裝了 IronPDF 庫。 要安裝 IronPDF 庫,請按照以下步驟操作: 在 Visual Studio 中開啟包管理器控制台。 輸入以下命令以使用 NuGet 安裝 IronPDF 庫: Install-Package IronPdf 或者,您可以通過在終端中運行以下命令來使用 .NET CLI: Install-Package IronPdf 按 Enter 執行命令。 這將下載並安裝 IronPDF 包到您的專案中。 也可以使用 NuGet 包管理器 GUI 安裝 IronPDF 庫。 只需在 Browse 標籤中搜尋套餐“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 此範例演示了一種簡單的方法來設置 Microsoft.Extensions.Logging,以用於使用 IronPDF 的 C# 應用程式中。 生成日誌消息以記錄 PDF 的成功創建以及可能發生的異常。 請確保根據您的應用程式的具體需求,以及在創建或修改 PDF 的場景中使用 IronPDF 自定義日誌級別、錯誤處理和消息。 適當區分不同類型的日誌訊息以有效的調試和監控。 欲了解更多有關 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 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 Cefsharp.WPF.NET Core(開發者的工作原理)Serilog .NET(開發者的工作...