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

Prism Logging (How It Works For Developers)

Console applications, despite their lack of a graphical user interface, often require robust logging mechanisms to track errors, monitor application performance, and debug issues efficiently. Prism.Plugin.Logging, an extension of the Prism Logging framework, offers a comprehensive logging solution for .NET applications, including support for various logging providers.

In this article, we explore how to integrate Prism Logging into console applications using IronPDF, a powerful .NET library for working with PDF documents. By combining these tools, developers can implement advanced logging functionality in their console applications, enhancing maintenance and troubleshooting capabilities.

Introduction to Prism Logging

Prism.Plugin.Logging extends Prism, a popular framework for building XAML applications, by providing comprehensive logging capabilities. With support for multiple logging providers such as NLog, Serilog, and Microsoft.Extensions.Logging, Prism.Plugin.Logging offers flexibility and customization options to suit various application requirements.

Advantages of using Prism logging

Flexible Logging Configuration: Prism.Plugin.Logging allows developers to configure various logging providers seamlessly, including popular options like NLog, Serilog, and Microsoft.Extensions.Logging.

Structured Logging Support: Developers can log-structured data with their messages using Prism.Plugin.Logging. This function is especially helpful in scenarios involving console applications where comprehensive context data, including timestamps, error codes, or user activities, must be recorded and added to log reports produced by IronPDF.

How to use Prism logging

  1. Create a new C# project
  2. Install the Prism logging package.
  3. Create an object for the SyslogLogger and pass the configuration as the parameter.
  4. Call the log method whenever required and pass the log message and logging level.
  5. Dispose of the log object at the end.

Getting Started With Prism Logs

Setting up Prism in C# Projects

Integrating Prism into a C# project is easy. Utilizing NuGet, Microsoft's .NET package manager is necessary in order to add Prism. The tools and libraries needed to incorporate Prism Logs into your projects are provided by this library.

Prism Logging (How It Works For Developers): Figure 1 - Install Prism using the Manage NuGet Package for Solution by searching "Prism.Plugin.Logging.Loggly" in the search bar of NuGet Package Manager, then select the project and click on the Install button.

Implementing Prism in Dot .NET Applications

Prism is compatible with a number of Dot .NET application types, including Windows Forms (WinForms) and Windows Console. Although each framework is implemented differently, the basic concept is always the same, assisting us in logging the data related to your application.

Creating a New Project in Visual Studio

Choose the File menu in the Visual Studio application. Click "New Project," then choose "Console application."

Prism Logging (How It Works For Developers): Figure 2 - Open Visual Studio and Select "New Project"- Select "Console App"

Enter the project name in the designated text area after selecting the file location. Then, as shown in the sample below, select the necessary .NET Framework by clicking the Create button.

Prism Logging (How It Works For Developers): Figure 3 - Next, configure you project by specifying the desired project name and location. Select the corresponding .NET Framework for your project and click on "Create" button.

The chosen application will then determine how the Visual Studio project is organized. Simply open the program.cs file to begin adding code to the application and building it. You can use Windows, the console, or the web application.

After this, the library may be added and the code tested.

A Basic Example of Using Prism Logs

In the code example below, we initialize the Prism log object and then add different logging levels one by one into the Prism logs, saving all the logs and their criticality into a list.

using Prism.Logging.Syslog;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

class Program
{
    public class Demo
    {
        public string Name { get; set; }
        public int Age { get; set; }

        // Configure the logger options
        static Options genOptions = new Options
        {
            HostNameOrIp = "127.0.0.1",
            Port = 514,
            AppNameOrTag = "LoggingDemo"
        };

        static SyslogLogger logger = new SyslogLogger(genOptions);
        static IList<LogData> Loglst = new List<LogData>();

        static async Task Main(string[] args)
        {
            MessageLog("Application started.", Prism.Logging.Syslog.Level.Information);
            PerformApplicationLogic();
            MessageLog("Application stopped.", Prism.Logging.Syslog.Level.Information);
        }

        static void PerformApplicationLogic()
        {
            // Example application logic
            Console.WriteLine("Performing application logic...");

            // Simulate error
            try
            {
                throw new Exception("Simulated Exception");
            }
            catch (Exception ex)
            {
                MessageLog($"Error occurred: {ex.Message}", Prism.Logging.Syslog.Level.Error);
            }
        }

        // Logs messages and their levels
        static void MessageLog(string message, Prism.Logging.Syslog.Level level)
        {
            Loglst.Add(new LogData { Message = message, Level = level.ToString() });
            logger.Log(message, level);
        }

        public class LogData
        {
            public string Message { get; set; }
            public string Level { get; set; }
        }

        public class Options : ISyslogOptions
        {
            public string HostNameOrIp { get; set; }
            public int? Port { get; set; }
            public string AppNameOrTag { get; set; }
        }
    }
}
using Prism.Logging.Syslog;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

class Program
{
    public class Demo
    {
        public string Name { get; set; }
        public int Age { get; set; }

        // Configure the logger options
        static Options genOptions = new Options
        {
            HostNameOrIp = "127.0.0.1",
            Port = 514,
            AppNameOrTag = "LoggingDemo"
        };

        static SyslogLogger logger = new SyslogLogger(genOptions);
        static IList<LogData> Loglst = new List<LogData>();

        static async Task Main(string[] args)
        {
            MessageLog("Application started.", Prism.Logging.Syslog.Level.Information);
            PerformApplicationLogic();
            MessageLog("Application stopped.", Prism.Logging.Syslog.Level.Information);
        }

        static void PerformApplicationLogic()
        {
            // Example application logic
            Console.WriteLine("Performing application logic...");

            // Simulate error
            try
            {
                throw new Exception("Simulated Exception");
            }
            catch (Exception ex)
            {
                MessageLog($"Error occurred: {ex.Message}", Prism.Logging.Syslog.Level.Error);
            }
        }

        // Logs messages and their levels
        static void MessageLog(string message, Prism.Logging.Syslog.Level level)
        {
            Loglst.Add(new LogData { Message = message, Level = level.ToString() });
            logger.Log(message, level);
        }

        public class LogData
        {
            public string Message { get; set; }
            public string Level { get; set; }
        }

        public class Options : ISyslogOptions
        {
            public string HostNameOrIp { get; set; }
            public int? Port { get; set; }
            public string AppNameOrTag { get; set; }
        }
    }
}
$vbLabelText   $csharpLabel

Log reports are generated from Prism Logging. We are using a tool called Kiwi Syslog Service Manager to monitor the Prism logs.

Output Prism Log file

Prism Logging (How It Works For Developers): Figure 4 - Monitoring the generated Prism log reports using the Kiwi Syslog Service Manager tool.

Prism Logs Operations

Extensible Logging

Prism.Plugin.Logging's capabilities are expanded via logging, which provides more functionality and flexibility. It offers a range of configuration options to adjust log levels, log targets, and other variables to meet the logging needs of your application.

Multiple Log Targets

You may route log messages to a variety of locations, including the console, files, databases, and other logging services, with Prism.Plugin.Logging. Because of this flexibility, you can select the best logging targets for the requirements and environment of your application.

Custom Loggers

With the plugin, you can implement Prism's ILoggerFacade interface to construct custom loggers. This lets you construct custom logging capabilities based on the needs of your application or interface with third-party logging frameworks.

Create Log with Prism Logs

Prism logs can be easily created with a few lines of code. Below is the sample to create a log.

static Options genOptions = new Options
{
    HostNameOrIp = "127.0.0.1",
    Port = 514,
    AppNameOrTag = "LoggingDemo"
};
static SyslogLogger logger = new SyslogLogger(genOptions);
logger.Log("Sample message", Prism.Logging.Syslog.Level.Information);
static Options genOptions = new Options
{
    HostNameOrIp = "127.0.0.1",
    Port = 514,
    AppNameOrTag = "LoggingDemo"
};
static SyslogLogger logger = new SyslogLogger(genOptions);
logger.Log("Sample message", Prism.Logging.Syslog.Level.Information);
$vbLabelText   $csharpLabel

Integrating Prism Logging and IronPDF

Using Prism and IronPDF Together

Combining Prism with IronPDF in a C# project opens some exciting possibilities. IronPDF is a fantastic tool for converting this content into PDFs, even though Prism is a great tool for working with logs. Programmers can create apps that log the item into a custom-designed PDF document because of this connectivity.

Prism Logging with IronPDF

By creating a Windows console application that utilizes Prism Logs, users can engage with the Logs inside your program. This control should fit on the console with plenty of room left over to make logs. Add server log operations and HTTP logs.

Install IronPDF

  • Open the Visual Studio project.
  • Choose "Tools" > "NuGet Package Manager" > "Package Manager Console".

    • In the Package Manager Console, type the following command and press Enter:
    Install-Package IronPdf
  • Another way to install IronPDF is using NuGet Package Manager for Solutions.
    • Browse the IronPDF package in the search results, select it, then click on the "Install" button. Visual Studio will handle the download and installation automatically.

Prism Logging (How It Works For Developers): Figure 5 - Install IronPDF using the Manage NuGet Package for Solution by searching "IronPdf" in the search bar of NuGet Package Manager, then select the project and click on the Install button.

  • NuGet will download and install the IronPDF package and any dependencies required for your project.
  • Once IronPDF has been installed, you can use it for your project.

Install Through the NuGet Website

Visit the IronPDF page at https://www.nuget.org/packages/IronPdf on the NuGet website to learn more about IronPDF's features, compatibility, and other download options.

Utilize DLL to Install

Alternatively, you can incorporate IronPDF directly into your project by using its DLL file. To download the ZIP file containing the DLL, click this link. Once it has been unzipped, include the DLL in your project.

Implementing the Logic

  • Setting Up the Renderer and Logger: The software sets up the IronPDF renderer and the Prism logger.
  • Logging Messages: Messages with a designated category and priority can be logged using the MessageLog() method. In this example, we log the application's start and stop messages as well as any exceptions that arise while the application is executing.
  • Applying Logic: A portion of application logic is simulated by the PerformApplicationLogic() method. To illustrate error logging, it merely produces a message and raises an exception in this case.
  • Creating a PDF Log Report: Following the execution of the application logic, the software creates an HTML document based on the recorded messages. It then uses IronPDF's RenderHtmlAsPdf() feature to transform the HTML document into a log file as a PDF report. The PDF file is then saved to disk.

Extending the previously defined code to integrate IronPDF code:

using IronPdf;

static void GeneratePdfLogReport()
{
    var renderer = new ChromePdfRenderer(); // Instantiates Chrome Renderer

    // Generate HTML content for PDF report
    string htmlContent = "<h1>Log Report</h1><ul>";
    foreach (var log in Loglst)
    {
        htmlContent += $"<li><strong>Message: {log.Message}</strong> Level: {log.Level}</li>";
    }
    htmlContent += "</ul>";

    // Generate PDF document
    var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

    // Save PDF file
    string filePath = "log_report.pdf";
    pdfDocument.SaveAs(filePath);
    Console.WriteLine($"PDF log report generated: {filePath}");
}
using IronPdf;

static void GeneratePdfLogReport()
{
    var renderer = new ChromePdfRenderer(); // Instantiates Chrome Renderer

    // Generate HTML content for PDF report
    string htmlContent = "<h1>Log Report</h1><ul>";
    foreach (var log in Loglst)
    {
        htmlContent += $"<li><strong>Message: {log.Message}</strong> Level: {log.Level}</li>";
    }
    htmlContent += "</ul>";

    // Generate PDF document
    var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

    // Save PDF file
    string filePath = "log_report.pdf";
    pdfDocument.SaveAs(filePath);
    Console.WriteLine($"PDF log report generated: {filePath}");
}
$vbLabelText   $csharpLabel

Below is the image log report generated from IronPDF

Prism Logging (How It Works For Developers): Figure 6 - Output PDF generated using IronPDF and data from Prism Log Report.

To know more about the IronPDF code references refer here.

Conclusion

Prism.Plugin.Logging integration with IronPDF allows developers to easily incorporate extensive logging capability into terminal apps. Developers can improve overall program maintenance, optimize debugging capabilities, and speed logging operations by utilizing the features of both tools. Prism.Plugin.Logging enables console applications to obtain complete logging coverage, guaranteeing strong monitoring and troubleshooting capabilities, with the right implementation and setup.

IronPDF offers a perpetual license of a Lite bundle that includes a permanent license, a year of software maintenance, and an upgrade of the library. IronPDF offers free licensing for development purposes, subject to restrictions on time and redistribution. To acquire the free trial. To find out more about the various Iron Software products, please visit their website link.

자주 묻는 질문

.NET 콘솔 애플리케이션에 로깅을 통합하려면 어떻게 해야 하나요?

다양한 로깅 제공업체를 지원하고 구조화된 로깅 프레임워크를 제공하는 Prism.Plugin.Logging을 사용하여 로깅을 .NET 콘솔 애플리케이션에 통합할 수 있습니다. 이를 설정하려면 Prism 로깅 패키지를 설치하고, 필요한 로깅 개체를 만든 다음 로깅 대상과 수준을 구성하세요.

프리즘 로깅과 IronPDF를 결합하면 어떤 이점이 있나요?

Prism 로깅과 IronPDF를 결합하면 PDF 로그 보고서를 생성하여 애플리케이션 유지 관리 및 문제 해결을 향상시킬 수 있습니다. IronPDF는 HTML 로그 콘텐츠를 PDF 문서로 변환하여 로그를 검토하고 공유할 수 있는 휴대용 형식을 제공합니다.

.NET에서 로그 데이터를 PDF 문서로 변환하려면 어떻게 해야 하나요?

.NET에서 로그 데이터를 PDF 문서로 변환하려면 IronPDF를 사용하여 로그 데이터를 HTML로 렌더링한 다음 RenderHtmlAsPdf와 같은 메서드를 사용하여 PDF로 변환하세요. 이렇게 하면 상세하고 휴대 가능한 로그 보고서를 만들 수 있습니다.

어떤 로깅 제공업체가 Prism.Plugin.Logging과 호환되나요?

Prism.Plugin.Logging은 NLog, Serilog 및 Microsoft.Extensions.Logging을 비롯한 여러 로깅 제공업체와 호환됩니다. 이러한 유연성 덕분에 개발자는 프로젝트의 요구 사항에 가장 적합한 로깅 공급자를 선택할 수 있습니다.

Visual Studio에서 Prism 로깅 프로젝트를 설정하려면 어떻게 해야 하나요?

Visual Studio에서 Prism 로깅 프로젝트를 설정하려면 새 C# 프로젝트를 만들고, NuGet 패키지 관리자를 사용하여 Prism 로깅 패키지를 설치한 다음, SyslogLogger 개체를 생성하고 로그 수준 및 대상을 구성하여 로깅 프레임워크를 초기화합니다.

사용자 지정 로깅 구성에 Prism.Plugin.Logging을 사용할 수 있나요?

예, Prism.Plugin.Logging은 사용자 지정 로깅 구성을 지원합니다. 로그 수준을 조정하고, 사용자 지정 로거를 정의하고, 로그 메시지를 다양한 대상으로 라우팅하여 특정 애플리케이션 요구 사항을 충족하는 맞춤형 로깅 설정을 할 수 있습니다.

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

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

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