Microsoft Logging C#(開發者的工作原理)
日誌是 C# 的基本技術,可在應用程式執行時擷取資訊、警告、錯誤和其他相關資料。 它可以幫助開發人員留意他們的程式如何運作、排除故障,以及理解應用程式在各種情況下如何運作。 C# 提供了一些日誌框架和套件,讓日誌工作變得更容易。 Microsoft.Extensions.Logging 是 .NET Core 應用程式中使用最廣泛的記錄框架之一。 適用於 .NET Core 的 Microsoft.Extensions.Logging NuGet 套件可讓我們存取數個擴充方法,以協助我們撰寫不同的日誌層級。 在本文中,我們將進一步了解 MS logging。
如何設定 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:將 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>()步驟 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)步驟 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")步驟 6:執行程式碼
最後,執行您的程式碼,觀察依照設定輸出的日誌。
就是這樣! 您已在 C# 應用程式中成功設定並使用 MS 日誌。
安裝 MS Logging
若要安裝 MS Logging,請遵循下列步驟:
1.啟動 Visual Studio。 2.導覽到 Tools > NuGet Package Manager > Package Manager Console。 3.在套件管理員控制台中,執行下列指令:
```powershell
Install-Package Microsoft.Extensions.Logging
```4.按下 Enter 執行指令。 這將會下載並安裝 Microsoft.Extensions.Logging 套件到您的專案中。
記錄層級
C# 中的 Microsoft.Extensions.Logging 框架提供了多種日誌等級,讓開發人員可以根據其重要性和嚴重性對日誌訊息進行分類和排序。 這些等級常用於區分各種訊息類型,並協助調節日誌的冗長程度。
Microsoft.Extensions.Logging 提供的預設記錄層級如下:
- 軌跡:最徹底的層級,通常用於提供令人難以置信的詳細資料,以深入瞭解程式的內部運作。
- 除錯:在開發和除錯階段有用,但在生產環境中通常不需要的除錯資訊。
- 資訊:提供應用程式如何正常運作的詳細資訊。 通常,會使用這些日誌來監控程式的正常運作。
- 警告:指出可能發生的問題或未來可能需要注意的事項。 它用於可能導致問題但不一定會導致程式當機的異常或意外情況。
- 錯誤:表示需要立即修正的嚴重問題或錯誤。 通常用來記錄影響應用程式運作的問題。
- 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在本範例中,控制台記錄器被新增至記錄設定,將記錄寫入控制台。 然而,Microsoft.Extensions.Logging 提供了多種記錄提供者,包括記錄到檔案、資料庫或連結到其他記錄框架。 此外,還可以建立自訂的日誌提供者,可根據特定需求格式化日誌。
包含額外的日誌提供者
您可以透過在 Create() 函式中鏈結相關的方法來新增額外的記錄來源。 舉例來說
- 若要新增除錯器輸出記錄提供者,請使用
builder.AddDebug()。 - 若要新增檔案記錄提供者,請使用
builder.AddFile("log.txt")。
IronPDF 上的MSLogging。
IronPdf 擅長於 HTML 至 PDF 的轉換,可確保精確保留原始版面與樣式。 它非常適合從網頁內容(如報告、發票和文件)建立 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");
}
}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要在 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在這個範例中,我們從 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
3.按下 Enter 執行指令。 這將會下載 IronPdf 套件並安裝到您的專案中。
也可以使用 NuGet Package Manager GUI 安裝 IronPDF 函式庫。 只需在 "瀏覽 "標籤中搜尋套件 "IronPDF",從清單中選擇所需套件,並安裝最新版本的 IronPDF 即可。
安裝完成後,您就可以開始在專案中使用 IronPDF 函式庫。
使用 IronPdf 進行MS 日誌記錄。
截至 2022 年 1 月,IronPdf 並未直接與 Microsoft.Extensions.Logging 進行互動,且不受本機支援。 IronPDF 主要用作在 C# 程式中建立和修改 PDF 的工具。
不過,您仍可以結合使用 Microsoft.Extensions 的日誌。 將日誌功能與 IronPDF 一同整合到 C# 程式中,您就可以管理並記錄與 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本範例示範在使用 IronPDF 的 C# 應用程式中設定 Microsoft.Extensions.Logging 的簡單方法。 會產生記錄訊息,以記錄成功建立 PDF 的過程,並記錄可能發生的任何異常。
請務必根據您應用程式的特定需求,以及 IronPDF 用於 PDF 創建或修改的場景,自訂記錄層級、錯誤處理和訊息。 使用日誌層級正確區分不同類型的日誌訊息,有助於有效的除錯和監控。
要瞭解 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 提供了追蹤、除錯、資訊、警告、錯誤和關鍵等日誌層級。這些層級可協助開發人員根據嚴重性和重要性來分類日誌訊息。
如何在 .NET Core 應用程式中注入 ILogger 介面?
在 .NET Core 應用程式中,您可以使用依賴注入的方式注入 ILogger 介面。這包括在您的 Startup 類別中設定服務容器,以包含記錄服務,然後將 ILogger
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 的產生過程。開發人員可追蹤應用程式事件、錯誤和效能問題,進而提升可靠性並簡化故障排除。







