푸터 콘텐츠로 바로가기
.NET 도움말

Microsoft Logging C# (How It Works For Developers)

Logging is an essential technique in C# that captures information, warnings, errors, and other pertinent data while an application is running. It aids developers in keeping an eye on how their programs behave, troubleshooting problems, and comprehending how the application functions in various contexts. C# offers some logging frameworks and packages to make logging jobs easier. Microsoft.Extensions.Logging is among the most widely used logging frameworks in .NET Core applications. The Microsoft.Extensions.Logging NuGet package for .NET Core gives us access to several extension methods to help us write different log levels. In this article, we are going to see more about MS logging.

How to Set Up MS Logging

  1. Create a new Visual Studio project.
  2. Install the Microsoft.Extensions.Logging library from the Microsoft.Extensions.Logging package page on NuGet.
  3. Inject the Logger interface into the console.
  4. Configure the logging output.
  5. Write logs at different levels.
  6. Run the code.

Step 1: Create a new Visual Studio project

To get started, create a new project in Visual Studio.

Step 2: Install the Microsoft.Extensions.Logging library

Install the Microsoft.Extensions.Logging library using the Microsoft.Extensions.Logging package page on NuGet. This library provides the necessary classes and methods for logging in .NET Core applications.

Step 3: Inject the Logger interface into the console

To use the logging functionality, you need to inject an instance of the ILogger interface into your console application. This can be done by using a logging factory.

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>();
$vbLabelText   $csharpLabel

Step 4: Configure the logging output

Configure how the logs should be output. This can be done by adding one or more logging providers to the logger builder. The most common provider is the console logger, which outputs the logs to the console.

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
});
$vbLabelText   $csharpLabel

Step 5: Write logs at different levels

You can now write logs at different levels using the logger object. The logging methods available are LogDebug(), LogInformation(), LogWarning(), LogError(), and 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");
$vbLabelText   $csharpLabel

Step 6: Run the code

Finally, run your code and observe the logs being output according to the configured settings.

That's it! You have successfully set up and used MS logging in your C# application.

Install MS Logging

To install MS Logging, follow these steps:

  1. Launch Visual Studio.
  2. Navigate to Tools > NuGet Package Manager > Package Manager Console.
  3. In the Package Manager Console, execute the following command:

    Install-Package Microsoft.Extensions.Logging
  4. Press Enter to execute the command. This will download and install the Microsoft.Extensions.Logging package into your project.

Logging Levels

Several logging levels are available in the Microsoft.Extensions.Logging framework in C#, enabling developers to classify and rank log messages according to their significance and severity. These levels are frequently used to distinguish between various message types and assist in regulating the verbosity of logs.

The default logging levels offered by Microsoft.Extensions.Logging are as follows:

  • Trace: The most thorough level, often employed for incredibly detailed data that offers a deep level of understanding of the inner workings of the program.
  • Debug: Debugging information that is useful during the development and debugging stages but is often not required in a production setting.
  • Information: Offers details on how the application functions normally. Usually, the regular operation of the program is monitored using these logs.
  • Warning: Points to a possible problem or anything that may require attention in the future. It is used for anomalous or unexpected situations that could result in issues but don't necessarily cause the program to crash.
  • Error: Signals a serious problem or mistake that needs to be fixed immediately. Usually used to record issues that affect the application's operation.
  • Critical: The most severe state, used to record critical problems that need to be addressed immediately since they might cause serious issues or program crashes.

Each log level serves a specific purpose and provides developers with the ability to manage the amount of data the logging framework outputs. Developers can choose the appropriate level for message recording based on the severity and importance of the logged data.

Configuring C# Logging

Here is a basic example of how to configure logging using 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
    }
}
$vbLabelText   $csharpLabel

In this example, a console logger is added to the logging configuration, which writes logs to the console. However, Microsoft.Extensions.Logging offers various logging providers, including logging to files, databases, or connecting with other logging frameworks. Additionally, it is possible to create custom logging providers that can format logs according to specific requirements.

Including Extra Providers for Logging

You can add additional logging sources by chaining the relevant methods within the Create() function. For example:

  • To add a debugger output logging provider, use builder.AddDebug().
  • To add a file logging provider, use builder.AddFile("log.txt").

MSLogging on IronPDF

IronPDF excels in HTML to PDF conversion, ensuring precise preservation of original layouts and styles. It's perfect for creating PDFs from web-based content such as reports, invoices, and documentation. With support for HTML files, URLs, and raw HTML strings, IronPDF easily produces high-quality PDF documents.

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");
    }
}
$vbLabelText   $csharpLabel

To enable logging in IronPDF, you can use the Microsoft.Extensions.Logging framework along with IronPDF's built-in logging capabilities. Here's an example of how to set up logging in 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();
    }
}
$vbLabelText   $csharpLabel

In this example, we create an instance of the LoggerFactory from the Microsoft.Extensions.Logging framework. We then create a logger from the factory for the Program class.

To enable logging in IronPDF, we set the static Logger.Log property to an instance of LoggerImplementation that takes the logger from loggerFactory. With this configuration, you can use Logger.Log methods to log messages within IronPDF.

After performing the necessary operations with IronPDF, you can close and dispose of resources, and then flush the log messages by disposing of the loggerFactory.

Note: Ensure that you have the necessary dependencies and packages installed for Microsoft.Extensions.Logging and IronPDF.

Install IronPDF

To install the IronPDF library, follow these steps:

  1. Open the Package Manager Console in Visual Studio.
  2. Enter the following command to install the IronPDF library using NuGet:
Install-Package IronPdf

Alternatively, you can use the .NET CLI by running the following command in the terminal:

Install-Package IronPdf
  1. Press Enter to execute the command. This will download and install the IronPDF package into your project.

It is also possible to install the IronPDF library using the NuGet Package Manager GUI. Simply search for the package "IronPDF" in the Browse tab, select the desired package from the list, and install the latest version of IronPDF.

Once the installation is complete, you can start using the IronPDF library in your project.

MS Logging using IronPDF

As of January 2022, IronPDF does not directly interact with Microsoft.Extensions.Logging and is not natively supported. IronPDF is primarily used as a tool for creating and modifying PDFs in C# programs.

However, you can still incorporate logging using Microsoft.Extensions. By integrating logging into your C# program alongside IronPDF, you can manage and log events related to PDF production, application workflow, or issues that occur when using IronPDF.

Here's an example of how to use Microsoft.Extensions to integrate logging with 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
    }
}
$vbLabelText   $csharpLabel

This sample demonstrates a simple way to set up Microsoft.Extensions.Logging within a C# application that uses IronPDF. Logging messages are generated to document the successful creation of PDFs and to record any exceptions that may occur.

Make sure to customize the logging levels, error handling, and messages according to the specific needs of your application and the scenarios in which IronPDF is used for PDF creation or modification. Properly differentiating between different types of log messages using logging levels can be useful for effective debugging and monitoring.

To learn more about IronPDF, please visit the IronPDF homepage,.

Conclusion

In conclusion, integrating Microsoft.Extensions.Logging allows C# developers to effectively handle logging tasks. IronPDF provides comprehensive logging capabilities, enabling thorough recording, analysis, and reporting of application events, failures, and vital data. This enhances application dependability, maintenance, and debugging.

IronPDF offers different software products, including a Lite bundle priced at $799. This bundle includes a permanent license, upgrade options, one year of software maintenance, and a thirty-day money-back guarantee. During the watermarked trial period, you can explore the features of IronPDF. To learn more about the software products offered by Iron Software, please visit Iron Software's official website.

자주 묻는 질문

.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 클래스에서 서비스 컨테이너를 구성한 다음 로깅이 필요한 클래스 유형이 T인 클래스에 ILogger를 주입하는 것이 포함됩니다.

IronPDF는 Microsoft.Extensions.Logging 프레임워크와 함께 작동할 수 있나요?

예, IronPDF는 Microsoft.Extensions.Logging과 통합할 수 있습니다. 로거를 설정하면 로깅 기능과 함께 IronPDF의 기본 기능을 사용하여 PDF 생성 중 애플리케이션 이벤트 및 문제를 추적하고 관리할 수 있습니다.

Microsoft.Extensions.Logging에 대한 로깅 출력을 어떻게 구성하나요?

로거 빌더에 로깅 공급자를 추가하여 로깅 출력을 구성합니다. 예를 들어 builder.AddConsole()를 사용하면 콘솔 출력을 구성하고, builder.AddDebug() 또는 builder.AddFile()를 사용하면 로그를 다른 대상으로 전송할 수 있습니다.

애플리케이션 개발에 로그인하는 목적은 무엇인가요?

애플리케이션 개발에 로그인하면 애플리케이션 동작을 모니터링하고 문제를 진단하며 다양한 맥락에서 애플리케이션 기능을 이해하는 데 도움이 됩니다. 특히 HTML에서 PDF로의 변환과 같은 특정 작업을 위해 IronPDF와 같은 도구를 통합할 때 애플리케이션의 안정성을 디버깅하고 유지하는 데 중요합니다.

C#을 사용하여 HTML을 PDF로 변환하는 단계에는 어떤 것이 있나요?

C#을 사용하여 HTML을 PDF로 변환하려면 IronPDF를 사용할 수 있습니다. 먼저 NuGet을 통해 IronPDF가 설치되어 있는지 확인합니다. 그런 다음 RenderHtmlAsPdf와 같은 IronPDF의 API 메서드를 사용하여 HTML 문자열 또는 파일을 PDF로 변환하고 프로세스 모니터링을 위해 로깅을 활용합니다.

프로젝트에서 로깅을 IronPDF와 통합하면 어떤 이점이 있나요?

프로젝트에서 로깅을 IronPDF와 통합하면 PDF 생성 프로세스를 더 잘 모니터링하고 디버깅할 수 있습니다. 개발자는 애플리케이션 이벤트, 오류 및 성능 문제를 추적할 수 있으므로 안정성이 향상되고 문제 해결이 간소화됩니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.