.NET HELP

Prism Logging (How It Works For Developers)

Published April 29, 2024
Share:

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 Logs with Prism.

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

using Prism.Logging.Syslog;
class Program
{
    public class Demo
    {
        public string name { get; set; }
        public int age { get; set; }
        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 started.", Prism.Logging.Syslog.Level.Information);
        }
        static void PerformApplicationLogic()
        {
            // Example application logic
            Console.WriteLine("Performing application logic...");
            // Simulate error
            try
            {
                throw new Exception();// This will throw an exception
            }
            catch (Exception ex)
            {
                MessageLog($"Error occurred: {ex.Message}", Prism.Logging.Syslog.Level.Error);
            }
        }
        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;
class Program
{
    public class Demo
    {
        public string name { get; set; }
        public int age { get; set; }
        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 started.", Prism.Logging.Syslog.Level.Information);
        }
        static void PerformApplicationLogic()
        {
            // Example application logic
            Console.WriteLine("Performing application logic...");
            // Simulate error
            try
            {
                throw new Exception();// This will throw an exception
            }
            catch (Exception ex)
            {
                MessageLog($"Error occurred: {ex.Message}", Prism.Logging.Syslog.Level.Error);
            }
        }
        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; }
        }
    }
}
Imports Prism.Logging.Syslog
Friend Class Program
	Public Class Demo
		Public Property name() As String
		Public Property age() As Integer
		Private Shared genOptions As New Options With {
			.HostNameOrIp = "127.0.0.1",
			.Port = 514,
			.AppNameOrTag = "LoggingDemo"
		}
		Private Shared logger As New SyslogLogger(genOptions)
		Private Shared Loglst As IList(Of LogData) = New List(Of LogData)()
		Shared Async Function Main(ByVal args() As String) As Task
			MessageLog("Application started.", Prism.Logging.Syslog.Level.Information)
			PerformApplicationLogic()
			MessageLog("Application started.", Prism.Logging.Syslog.Level.Information)
		End Function
		Private Shared Sub PerformApplicationLogic()
			' Example application logic
			Console.WriteLine("Performing application logic...")
			' Simulate error
			Try
				Throw New Exception() ' This will throw an exception
			Catch ex As Exception
				MessageLog($"Error occurred: {ex.Message}", Prism.Logging.Syslog.Level.Error)
			End Try
		End Sub
		Private Shared Sub MessageLog(ByVal Message As String, ByVal _level As Prism.Logging.Syslog.Level)
			Loglst.Add(New LogData With {
				.message = Message,
				.Level = _level.ToString()
			})
			logger.Log(Message, _level)
		End Sub
		Public Class LogData
			Public Property message() As String
			Public Property Level() As String
		End Class
		Public Class Options
			Implements ISyslogOptions

			Public Property HostNameOrIp() As String
			Public Property Port() As Integer?
			Public Property AppNameOrTag() As String
		End Class
	End Class
End Class
VB   C#

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.Prism's logging 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(Message, _level);
static Options genOptions = new Options
{
        HostNameOrIp = "127.0.0.1",
        Port = 514,
        AppNameOrTag = "LoggingDemo"
};
static SyslogLogger logger = new SyslogLogger(genOptions);
logger.Log(Message, _level);
Private Shared genOptions As New Options With {
	.HostNameOrIp = "127.0.0.1",
	.Port = 514,
	.AppNameOrTag = "LoggingDemo"
}
Private Shared logger As New SyslogLogger(genOptions)
logger.Log(Message, _level)
VB   C#

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(ChromePdfRenderer Renderer)
{
    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>{log.message}:</strong> {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(ChromePdfRenderer Renderer)
{
    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>{log.message}:</strong> {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}");
}
Imports IronPdf
Shared Sub GeneratePdfLogReport(ByVal Renderer As ChromePdfRenderer)
	Dim Renderer = New ChromePdfRenderer() ' Instantiates Chrome Renderer
		' Generate HTML content for PDF report
		Dim htmlContent As String = "<h1>Log Report</h1><ul>"
		For Each log In Loglst
			 htmlContent &= $"<li><strong>{log.message}:</strong> {log.Level}</li>"
		Next log
		htmlContent &= "</ul>"
		' Generate PDF document
		Dim pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent)
		' Save PDF file
		Dim filePath As String = "log_report.pdf"
		pdfDocument.SaveAs(filePath)
		Console.WriteLine($"PDF log report generated: {filePath}")
End Sub
VB   C#

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 $749 Lite bundle that comes with 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.

< PREVIOUS
TCP .NET (How It Works For Developers)
NEXT >
Npgsql C# (How It Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >