Microsoft Logging C#(開發者的工作原理)
日誌是 C# 的基本技術,可在應用程式執行時擷取資訊、警告、錯誤和其他相關資料。 它可以幫助開發人員留意他們的程式如何運作、排除故障,以及理解應用程式在各種情況下如何運作。 C# 提供了一些日誌框架和套件,讓日誌工作變得更容易。 Microsoft.Extensions.Logging 是 .NET Core 應用程式中使用最廣泛的記錄框架之一。 .NET Core 的 Microsoft.Extensions.Logging NuGet 套件為我們提供了幾個擴充方法,以幫助我們編寫不同等級的日誌。 在本文中,我們將進一步了解 MS logging。
如何設定 MS 記錄。
1.建立一個新的 Visual Studio 專案。
- 從NuGet 上的 Microsoft.Extensions.Logging 套件頁面安裝
Microsoft.Extensions.Logging庫。 - 將
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 提供的預設日誌等級如下:
*追蹤:*最徹底的級別,通常用於極其詳細的數據,可以深入了解程式的內部運作。 調試資訊:在開發和調試階段很有用的調試信息,但在生產環境中通常不需要。 資訊:提供有關應用程式正常運作方式的詳細資訊。 通常,會使用這些日誌來監控程式的正常運作。 警告:指出可能存在的問題或將來可能需要注意的事項。 它用於可能導致問題但不一定會導致程式當機的異常或意外情況。 錯誤:表示有嚴重問題或錯誤,需要立即修復。 通常用來記錄影響應用程式運作的問題。 嚴重:**最嚴重的狀態,用於記錄需要立即解決的嚴重問題,因為它們可能會導致嚴重問題或程式崩潰。
每個日誌層級都有特定的目的,並提供開發人員管理日誌框架輸出的資料量。 開發人員可根據記錄資料的嚴重性和重要性,選擇適當的訊息記錄等級。
設定 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 提供不同的軟體產品,包括價格為 $999 的 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
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 生成過程。開發者可以跟蹤應用程式事件、錯誤和性能問題,從而提高可靠性並簡化故障排除。



