跳過到頁腳內容
.NET幫助

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

記錄是軟體開發的重要部分,尤其是在像 C# 這樣的語言中。 它幫助開發者追踪程式執行期間發生的事件,從而更易於理解其行為和診斷問題。 本指南將涵蓋 C# 記錄和IronPDF 進階 PDF 操作功能的所有方面,從基本概念到高級記錄配置和工具。 它提供了全面的理解和對應用程式中記錄配置的控制。

理解 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# 日誌(如何為開發者工作):圖 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 事件日誌)集成,增強日誌數據的管理和分析。 通過使用專門的記錄提供者,日誌訊息可以被定向到這些系統,從而提供更強大的錯誤監控和響應能力。

// 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 事件日誌,源名稱為“ MyApplication”。 這對於運行在 Windows 伺服器上的應用程式特別有用,因為事件日誌是一種監控軟體和系統消息的集中工具。

與 C# 記錄集成 IronPDF

C# 日誌(如何為開發者工作):圖 2 - IronPDF 首頁

了解更多有關 IronPDF 用於 HTML 到 PDF 轉換的信息是一個 .NET PDF 庫,允許開發者創建、操作和渲染 PDF 檔。 它將 HTML 轉換為 PDF,這是生成報告、發票和其他來自網頁內容的文檔類型的常見需求。 IronPDF 提供了一套全面的功能,以滿足各種 PDF 相關的任務,包括編輯文本和映像、保護檔案,甚至提取內容。

將 IronPDF 與 C# 記錄結合使用可以增強處理 PDF 文件的錯誤處理和調試功能。 通過集成記錄,您可以追踪 PDF 生成過程,並捕獲任何出現的問題或異常。這種集成在 PDF 生成作為應用程式功能的重要部分的情況下特別有用,例如根據用戶數據生成動態報告。

代碼示例

要將 IronPDF 與 C# 記錄一起使用,您需要在 PDF 操作中加入記錄調用。 以下是如何在 .NET 應用程式中集成這兩種技術的範例。 此範例假設您正在使用來自 Microsoft.Extensions.LoggingILogger 介面。

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# 日誌(如何為開發者工作):圖 3 - 與 IronPDF 集成後顯示訊息級日誌訊息的控制台輸出

此設置不僅促進了從 HTML 生成 PDF,還確保該操作通過日誌進行良好記錄,從而有助於維護和排除故障。 將記錄與 IronPDF 集成可以顯著提高應用程式 PDF 處理功能的可靠性和可追溯性。

結論

C# 日誌(如何為開發者工作):圖 4 - IronPDF 授權頁面

C# 中的記錄是一種靈活且強大的方式,可以捕獲有關您的應用程式運行的詳細信息。 通過使用不同的記錄級別、配置各種提供者以及實施結構化記錄,開發者可以創建一個全面的記錄系統,以改善其應用程式的可維護性和可調試性。

免費試用 IronPDF,起價$799。

常見問題解答

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

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。