DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

Structured Logging with Serilog

Serilog is a logging library known for its support of structured logs. It allows you to record logs with data in a more detailed and organized way, making it easier to query and analyze logs later. Serilog also offers easy integration with various platforms, including files, databases, and log monitoring services. In this example, we will see how to configure Serilog to generate logs in a file.

Libraries:

To use the Serilog library, install the following NuGet packages in your project:

Install-Package Serilog
Install-Package Serilog.Sinks.File
Enter fullscreen mode Exit fullscreen mode

Example Code:

using Serilog;
using System;

namespace SerilogExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Configuring Serilog to log to a file
            Log.Logger = new LoggerConfiguration()
                .WriteTo.File("serilog-log.txt")
                .CreateLogger();

            // Example logs
            Log.Information("The application has started.");
            Log.Warning("This is a warning.");
            Log.Error("An error occurred in the process.");

            Console.WriteLine("Logs generated. Check the serilog-log.txt file.");

            // Closing the logger
            Log.CloseAndFlush();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, we configure Serilog to write logs to a file named serilog-log.txt. We use the WriteTo.File method to set the log destination. Three types of logs are generated: Information, Warning, and Error. Each log is written to the file with structured details. Finally, we call Log.CloseAndFlush() to ensure all pending logs are written before the application closes.

Conclusion:

Serilog is a powerful tool for those who want to work with structured logs, allowing for richer and more organized data capture. With its easy configuration and integration with multiple platforms, Serilog is ideal for efficiently monitoring and debugging applications.

Source code: GitHub

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more