跳過到頁腳內容
.NET幫助

C# Logging(對於開發者的運行原理)

Logging 是軟體開發的重要部分,尤其是 C# 等語言。 它可以幫助開發人員追蹤程式執行過程中發生的事件,讓他們更容易瞭解程式的行為和診斷問題。 本指南將涵蓋 C# 日誌和 進階 PDF 操作功能的 IronPDF 的所有方面,從基本概念到進階日誌配置和工具。 它能讓您全面了解並控制應用程式中的日誌設定。

瞭解 C# 中的日誌記錄

C# 日誌的核心是在軟體執行時記錄相關資訊。 這些記錄或日誌訊息儲存在日誌檔案或其他媒介中,可能包括錯誤訊息、軟體狀態資訊或除錯訊息等資料。 記錄的目的是提供一種方式,以持久化的格式擷取應用程式運作的相關資訊。 這些資訊對於調試問題、監控軟體效能,以及確保應用程式的表現符合預期,都是非常寶貴的。 這包括配置檔案、日誌 API、日誌配置、結構化日誌和日誌異常。

撰寫日誌訊息

若要在 C# 中開始記錄日誌,開發人員需要在應用程式中撰寫日誌訊息。 這是透過使用日誌框架或 API 來完成的。 在 C# 中,一個受歡迎的選擇是 Microsoft 的 ILogger 介面,可在 Microsoft.Extensions.Logging 命名空間中取得。 此介面提供一種簡單的方式,可記錄不同重要性層級的資料,這些層級稱為日誌層級。 這些層級包括資訊、除錯和錯誤,有助於根據記錄訊息的嚴重程度來分類和過濾日誌輸出。

using Microsoft.Extensions.Logging;

public class Program
{
    static void Main(string[] args)
    {
        // Create a logger instance with console output
        ILogger logger = LoggerFactory.Create(builder => 
        {
            builder.AddConsole(); // Add console as a logging target
        }).CreateLogger<Program>();

        // Log messages with different levels of severity
        logger.LogInformation("This is an information log message");
        logger.LogError("This is an error log message");
    }
}
using Microsoft.Extensions.Logging;

public class Program
{
    static void Main(string[] args)
    {
        // Create a logger instance with console output
        ILogger logger = LoggerFactory.Create(builder => 
        {
            builder.AddConsole(); // Add console as a logging target
        }).CreateLogger<Program>();

        // Log messages with different levels of severity
        logger.LogInformation("This is an information log message");
        logger.LogError("This is an error log message");
    }
}
Imports Microsoft.Extensions.Logging

Public Class Program
	Shared Sub Main(ByVal args() As String)
		' Create a logger instance with console output
		Dim logger As ILogger = LoggerFactory.Create(Sub(builder)
			builder.AddConsole() ' Add console as a logging target
		End Sub).CreateLogger<Program>()

		' Log messages with different levels of severity
		logger.LogInformation("This is an information log message")
		logger.LogError("This is an error log message")
	End Sub
End Class
$vbLabelText   $csharpLabel

在上面的範例中,名為 loggerILogger 物件被設定為輸出日誌訊息到控制台。 這個設定很簡單,但卻是幫助您瞭解日誌訊息如何產生與顯示的基礎。

C# Logging (How It Works For Developers):圖 1 - 包含日誌訊息的控制台輸出範例

記錄檔與提供者

在實際應用中,您經常需要將日誌訊息儲存在檔案或其他儲存系統中,以便日後檢視。 這就是記錄提供者發揮作用的地方。 提供者是日誌框架的元件,用來處理日誌資料輸出到各種目的地,例如檔案、資料庫或外部服務。

例如,若要設定記錄器將訊息寫入檔案,您可能會使用類似 FileLoggerProvider的檔案型提供者。 這需要修改應用程式的組態檔案 (在 .NET 應用程式中通常為 appsettings.json),以指定日誌檔案路徑和最低日誌層級等細節。

{
  "Logging": {
    "LogLevel": {
      "Default": "Information", // Log levels for the application
      "Microsoft": "Warning"   // Log levels for Microsoft libraries
    },
    "File": {
      "Path": "logs/myapp.log" // File path for the log file
    }
  }
}

配置指定所有預設日誌應為"資訊"層級,但 Microsoft 的函式庫只應記錄警告及以上的日誌。 它還會將日誌輸出導向 logs 目錄中名為 myapp.log 的日誌檔案。

進階記錄技術

除了基本的日誌訊息之外,C# 還支援結構化日誌,可在日誌中包含結構化資料,而不只是純文字。 結構化日誌讓搜尋和分析日誌資料變得更容易,因為每項上下文資訊都會儲存為獨立的欄位。

// Log message with structured data
logger.LogDebug("Processing order {OrderId} at {Timestamp}", orderId, DateTime.UtcNow);
// Log message with structured data
logger.LogDebug("Processing order {OrderId} at {Timestamp}", orderId, DateTime.UtcNow);
' Log message with structured data
logger.LogDebug("Processing order {OrderId} at {Timestamp}", orderId, DateTime.UtcNow)
$vbLabelText   $csharpLabel

在這個結構化日誌範例中,OrderIdTimestamp是訊息範本中的占位符,將分別填入 orderIdDateTime.UtcNow 的值。 這比傳統的日誌功能更強大,因為它允許根據每個日誌項目內的特定欄位,更輕鬆地查詢和處理日誌資料。

與外部系統整合

C# 日誌可擴充至與 SQL Server 或 Windows Event Log 等外部系統整合,強化日誌資料的管理與分析方式。 透過使用專門的日誌提供者,日誌訊息可以直接傳送到這些系統,提供更強大的錯誤監控與回應能力。

// Direct log output to the Windows Event Log under a specific source name
builder.AddEventLog(new EventLogSettings
{
    SourceName = "MyApplication"
});
// Direct log output to the Windows Event Log under a specific source name
builder.AddEventLog(new EventLogSettings
{
    SourceName = "MyApplication"
});
' Direct log output to the Windows Event Log under a specific source name
builder.AddEventLog(New EventLogSettings With {.SourceName = "MyApplication"})
$vbLabelText   $csharpLabel

此設定片段會將日誌輸出導向 Windows Event Log,來源名稱為 "MyApplication"。 這對於在 Windows 伺服器上執行的應用程式特別有用,在 Windows 伺服器上,事件日誌是監控軟體和系統訊息的集中工具。

將 IronPDF 與 C# 日誌整合。

C# Logging (How It Works For Developers):圖 2 - IronPDF 首頁

Learn More About IronPDF for HTML to PDF Conversion 是一個 .NET PDF 函式庫,可讓開發人員建立、處理及渲染 PDF。 它可將 HTML 轉換為 PDF,這是從網頁內容產生報告、發票及其他文件類型的常見需求。 IronPDF 提供了一套全面的功能,可滿足各種 PDF 相關工作的需求,包括編輯文字和圖片、保護文件,甚至是擷取內容。

將 IronPDF 與 C# 日誌結合,可以增強處理 PDF 檔案時的錯誤處理與除錯功能。 透過整合記錄,您可以追蹤 PDF 的產生過程,並擷取任何問題或出現的異常。在 PDF 生成是應用程式功能的關鍵部分(例如根據使用者資料動態生成報告)的場景中,此整合尤其有用。

程式碼範例

要在使用 IronPDF 的同時使用 C# 日誌,您需要在 PDF 作業中加入日誌呼叫。 以下是如何在 .NET 應用程式中整合這兩種技術的範例。 本範例假設您使用 Microsoft.Extensions.Logging 中的 ILogger 介面。

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

public class PdfGenerator
{
    private readonly ILogger _logger;

    public PdfGenerator(ILogger<PdfGenerator> logger)
    {
        _logger = logger;
    }

    public void CreatePdfFromHtml(string htmlContent, string outputPath)
    {
        try
        {
            // Initialize PDF renderer
            var renderer = new ChromePdfRenderer();

            // Convert HTML content to PDF
            var pdf = renderer.RenderHtmlAsPdf(htmlContent);

            // Save the generated PDF to a file
            pdf.SaveAs(outputPath);

            // Log the success of PDF creation
            _logger.LogInformation("PDF created successfully at {OutputPath}", outputPath);
        }
        catch (Exception ex)
        {
            // Log any errors encountered during PDF creation
            _logger.LogError(ex, "Error creating PDF from HTML");
        }
    }
}

// Usage example
public class Program
{
    static void Main(string[] args)
    {
        // Set the license key for IronPDF, if applicable
        License.LicenseKey = "License-Key";

        // Create a logger factory to manage logging configurations
        ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
        {
            builder.AddConsole(); // Enable logging to the console
        });

        // Create a logger for the PdfGenerator class
        ILogger<PdfGenerator> logger = loggerFactory.CreateLogger<PdfGenerator>();

        // Instantiate the PDF generator
        PdfGenerator pdfGenerator = new PdfGenerator(logger);

        // Example HTML content and output path
        string htmlContent = "<h1>Hello, PDF!</h1><p>This is a simple PDF generated from HTML.</p>";
        string outputPath = "output.pdf";

        // Create a PDF from the provided HTML content
        pdfGenerator.CreatePdfFromHtml(htmlContent, outputPath);
    }
}
using IronPdf;
using Microsoft.Extensions.Logging;
using System;

public class PdfGenerator
{
    private readonly ILogger _logger;

    public PdfGenerator(ILogger<PdfGenerator> logger)
    {
        _logger = logger;
    }

    public void CreatePdfFromHtml(string htmlContent, string outputPath)
    {
        try
        {
            // Initialize PDF renderer
            var renderer = new ChromePdfRenderer();

            // Convert HTML content to PDF
            var pdf = renderer.RenderHtmlAsPdf(htmlContent);

            // Save the generated PDF to a file
            pdf.SaveAs(outputPath);

            // Log the success of PDF creation
            _logger.LogInformation("PDF created successfully at {OutputPath}", outputPath);
        }
        catch (Exception ex)
        {
            // Log any errors encountered during PDF creation
            _logger.LogError(ex, "Error creating PDF from HTML");
        }
    }
}

// Usage example
public class Program
{
    static void Main(string[] args)
    {
        // Set the license key for IronPDF, if applicable
        License.LicenseKey = "License-Key";

        // Create a logger factory to manage logging configurations
        ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
        {
            builder.AddConsole(); // Enable logging to the console
        });

        // Create a logger for the PdfGenerator class
        ILogger<PdfGenerator> logger = loggerFactory.CreateLogger<PdfGenerator>();

        // Instantiate the PDF generator
        PdfGenerator pdfGenerator = new PdfGenerator(logger);

        // Example HTML content and output path
        string htmlContent = "<h1>Hello, PDF!</h1><p>This is a simple PDF generated from HTML.</p>";
        string outputPath = "output.pdf";

        // Create a PDF from the provided HTML content
        pdfGenerator.CreatePdfFromHtml(htmlContent, outputPath);
    }
}
Imports IronPdf
Imports Microsoft.Extensions.Logging
Imports System

Public Class PdfGenerator
	Private ReadOnly _logger As ILogger

	Public Sub New(ByVal logger As ILogger(Of PdfGenerator))
		_logger = logger
	End Sub

	Public Sub CreatePdfFromHtml(ByVal htmlContent As String, ByVal outputPath As String)
		Try
			' Initialize PDF renderer
			Dim renderer = New ChromePdfRenderer()

			' Convert HTML content to PDF
			Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)

			' Save the generated PDF to a file
			pdf.SaveAs(outputPath)

			' Log the success of PDF creation
			_logger.LogInformation("PDF created successfully at {OutputPath}", outputPath)
		Catch ex As Exception
			' Log any errors encountered during PDF creation
			_logger.LogError(ex, "Error creating PDF from HTML")
		End Try
	End Sub
End Class

' Usage example
Public Class Program
	Shared Sub Main(ByVal args() As String)
		' Set the license key for IronPDF, if applicable
		License.LicenseKey = "License-Key"

		' Create a logger factory to manage logging configurations
		Dim loggerFactory As ILoggerFactory = LoggerFactory.Create(Sub(builder)
			builder.AddConsole() ' Enable logging to the console
		End Sub)

		' Create a logger for the PdfGenerator class
		Dim logger As ILogger(Of PdfGenerator) = loggerFactory.CreateLogger(Of PdfGenerator)()

		' Instantiate the PDF generator
		Dim pdfGenerator As New PdfGenerator(logger)

		' Example HTML content and output path
		Dim htmlContent As String = "<h1>Hello, PDF!</h1><p>This is a simple PDF generated from HTML.</p>"
		Dim outputPath As String = "output.pdf"

		' Create a PDF from the provided HTML content
		pdfGenerator.CreatePdfFromHtml(htmlContent, outputPath)
	End Sub
End Class
$vbLabelText   $csharpLabel

C# Logging (How It Works For Developers):圖 3 - 與 IronPDF 整合後,控制台輸出展示資訊等級的日誌訊息

此設定不僅有助於從 HTML 生成 PDF,還可確保透過日誌對操作進行詳細記錄,有助於維護和故障排除。 將日誌與 IronPDF 整合,可大幅提升應用程式 PDF 處理功能的可靠性與可追蹤性。

結論

C# Logging (How It Works For Developers):圖 4 - IronPDF 授權頁面

C# 日誌是擷取應用程式運作詳細資訊的靈活且強大的方式。 透過使用不同的日誌層級、設定各種提供者,以及實施結構化日誌,開發人員可以建立一個全面的日誌系統,以改善應用程式的可維護性和可除錯性性。

立即體驗 IronPDF,免費試用版起價為 $999。

常見問題解答

什麼是 C# 中的日誌記錄?

在 C# 中的日誌記錄涉及記錄軟體在執行過程中的操作信息。日誌消息存儲在日誌文件或其他媒介中,包括錯誤消息和調試消息數據,這有助於理解應用程式的行為和診斷問題。

為何日誌對開發者來說如此重要?

日誌至關重要,因為它提供了一種持久的方法來捕獲應用程式操作的信息。這些信息對於調試問題、監控軟體性能以及確保應用程式按預期運行非常有價值。

如何在 C# 中將日誌消息寫入文件?

要在 C# 中將日誌消息寫入文件,可以使用基於文件的提供者如 FileLoggerProvider。這涉及修改應用程式的配置文件,比如 appsettings.json 來指定日誌文件詳情及最低日誌級別。

什麼是 C# 中的結構化日誌?

C# 中的結構化日誌允許日誌中包括結構化數據而不是純文本。這使得搜索和分析日誌數據更為容易,因為每一段上下文信息都作為單獨的字段存儲,便於查詢和處理。

C# 日誌記錄如何與外部系統集成?

C# 日誌記錄可以通過使用專門的日誌提供者與外部系統如 SQL Server 或 Windows 事件日誌集成。這使得日誌消息可以被導向這些系統,增強錯誤監控和響應能力。

如何在 C# 應用程式中使用 PDF 庫?

PDF 庫可以用於 C# 應用程式中以創建、處理和渲染 PDF。它可以與 C# 日誌集成,以增強 PDF 操作過程中的錯誤處理和調試,比如追踪 PDF 生成過程和捕獲問題或異常。

如何將 PDF 庫與 C# 日誌集成?

要將 PDF 庫與 C# 日誌集成,可以在 PDF 操作中加入日誌調用。通過使用 ILogger 介面,可以記錄 PDF 創建過程的成功或失敗,從而有助於維護和故障排除。

C# 日誌中的日誌級別是什麼?

C# 日誌中的日誌級別是用來表示日誌消息的重要性或嚴重程度的類別。常見的日誌級別包括 Information、Debug 和 Error,用於根據日誌的上下文過濾和管理日誌數據。

C# 日誌能否用於監控軟件性能?

是的,C# 日誌可以通過捕獲應用程式操作的詳細信息來監控軟件性能。這些數據有助於識別性能問題並確保應用程式的最佳性能。

如何在 C# 中配置多個日誌提供者?

可以通過設置 ILoggerFactory 來包含各種提供者如控制台、文件和第三方服務以配置多個日誌提供者。這種配置允許日誌消息被導向多個目的地以實現全面監控。

有哪些 C# 日誌的高級技術?

C# 日誌的高級技術包括結構化日誌,這可以增強日誌數據分析,以及使用第三方提供者將日誌指向外部系統如雲服務。這些技術可以改善日誌管理和數據洞察。

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技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我