How to Implement Logging using Serilog in ASP.NET Core Web API

How to Implement Logging using Serilog in ASP.NET Core Web API

In this article, I will discuss how to implement logging using Serilog in the ASP.NET Core Web API Application, along with examples. Please read our previous article discussing How to Implement Default Logging in ASP.NET Core Web API. At the end of this article, you will understand the following pointers:

  1. What is Serilog in ASP.NET Core Web API?
  2. How Do We Implement Serilog in ASP.NET Core Web API?
  3. What are the options available for rollingInterval in Serilog?
  4. Structured Logging in ASP.NET Core Web API
  5. Structured Logging Using Serilog in ASP.NET Core Web API
  6. Centralizing the Serilog Configuration in AppSettings.JSON File
  7. Different Srinks Available with Serilog.
  8. When Should We Use Serilog in ASP.NET Core Web API?

What is Serilog in ASP.NET Core Web API?

Serilog is a popular, high-performance, structured logging library for .NET applications, including ASP.NET Core Web API projects. It is designed to be easy to configure, extend, and use, providing developers with a powerful tool to capture, analyze, and store logs in a structured, queryable format. This makes it easier to understand complex application flows, diagnose problems, and analyze how applications are being used.

In the context of an ASP.NET Core Web API, Serilog can be used to log HTTP requests, responses, exceptions, and any custom events or messages that developers wish to track. It supports logging to various sinks (outputs), such as consoles, files, databases, and more sophisticated log management systems like Seq, Elasticsearch, or Splunk.

Key Features of Serilog:
  • Structured Logging: Unlike traditional logging libraries that log messages as plain text, Serilog logs events in a structured format. This means each piece of data within a log message is captured as a discrete element, making it easier to search and analyze logs based on specific fields.
  • Multiple Sinks: Serilog supports logging to various destinations. Developers can log into files, the console, the debug window, and across the network to centralized log servers or services. This flexibility ensures that logs can be stored and analyzed in a manner that best suits the application’s requirements.
  • Performance: Designed with performance in mind, Serilog minimizes the impact of logging on application throughput and response times.

How Do We Implement Serilog in ASP.NET Core Web API?

Implementing Serilog in an ASP.NET Core Web API project is a straightforward process that significantly enhances your application’s logging capabilities. Here’s a step-by-step guide to implementing Serilog in your ASP.NET Core Web API project:

Step 1: Install Serilog NuGet Packages

First, you need to add Serilog along with its ASP.NET Core and sink-specific packages to your project. You can do this via the NuGet Package Manager or the Package Manager Console. Here are some common packages you might need:

  • Serilog.AspNetCore: This package is designed to integrate Serilog with ASP.NET Core applications seamlessly. It acts as a bridge between Serilog and ASP.NET Core, making it easier to configure and use Serilog as the logging provider.
  • Serilog.Sinks.Console: In Serilog terminology, a “sink” is an output destination for your logs. The Serilog.Sinks.Console package enables logging output to the console/terminal. This is particularly useful during development when you might want to see log output in real time as you run your application. Console sinks are often used in conjunction with other sinks to allow for both immediate visibility of logs and persistent storage.
  • Serilog.Sinks.File: Similar to the Console sink, the Serilog.Sinks.File package allows Serilog to write logs to files on disk. This is crucial for persistent logging, enabling the analysis of logs over time or after specific events have occurred. Logs stored in files can be reviewed later for troubleshooting, auditing, or monitoring the application’s behavior over time.
  • Serilog.Settings.Configuration: This package enables Serilog to be configured via the ASP.NET Core appsettings.json file. It allows for easy configuration and management of Serilog’s settings without hard-coding values in your application’s code. This includes configuring log levels, sinks, and other Serilog features dynamically based on the application’s running environment (e.g., Development, Staging, Production).
Installing the Packages Using Package Manager Console:

Install-Package Serilog.AspNetCore
Install-Package Serilog.Sinks.Console
Install-Package Serilog.Sinks.File
Install-Package Serilog.Settings.Configuration

Once you have installed the above Serilog Packages, your Packages folder should look as shown in the image below:

How Do We Implement Serilog in ASP.NET Core Web API?

Step 2: Configure Serilog in Program.cs

In the Program.cs file, configure Serilog. You need to do this at the beginning of the program’s execution before the host is built. The following code configures the application’s logging system using Serilog.

//Namespace
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Configure Serilog
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .WriteTo.File("logs/MyAppLog.txt")
    .CreateLogger();

builder.Host.UseSerilog(); // Use Serilog for logging

//Other services and middleware components

The following code snippet configures the Serilog logging library for use in an ASP.NET Core Web API project. It sets up how logging should be performed within the application, including where logs should be written and what additional data should be included with each log entry.

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .WriteTo.File("logs/MyAppLog.txt")
    .CreateLogger();

Here’s a breakdown of what each part of this configuration does:

  • Log.Logger = new LoggerConfiguration(): This line initiates the configuration of a new Serilog logger. Log.Logger is the static logger instance that will be used throughout the application to log messages.
  • .ReadFrom.Configuration(builder.Configuration): This tells Serilog to read its configuration settings from the application’s configuration system (typically appsettings.json files). This makes it easy to adjust logging settings without changing the code, such as changing the log level or adding new sinks. The builder.Configuration part is a reference to the application’s configuration builder, which accumulates all configuration sources.
  • .Enrich.FromLogContext(): Enrichers add additional information to log events. FromLogContext is an enricher that adds contextual information from the logging context to each log entry. This can include data like the HTTP request path, user identity, and any other contextual information you have added to the log context. It’s very useful for tracing and understanding the flow of operations, especially when diagnosing issues.
  • .WriteTo.Console(): This adds a logging sink that outputs log events to the console. This is useful during development and debugging because it allows developers to see log output in real-time directly in their console or terminal window.
  • .WriteTo.File(“logs/MyAppLog.txt”): This adds another logging sink that writes log events to a file named MyAppLog.txt in the logs directory. This ensures that logs persist in the disk, allowing for later review. Log files are crucial for troubleshooting issues after they occur, especially in production environments where console output is not accessible.
  • .CreateLogger();: Finally, this line builds the logger instance with the configured settings and assigns it to the static Log.Logger property. This configured logger is ready to be used throughout the application.
Integrating Serilog with the Host:

builder.Host.UseSerilog(); This line is used to configure the application’s host to use Serilog as its logging provider. This is an essential step in integrating Serilog into an ASP.NET Core application, allowing Serilog to capture logs from the framework and application code.

Step 3: Update appsettings.json

Please modify the appsettings.json file as follows. The following JSON is the configuration for the Serilog logging library within the ASP.NET Core application. It specifies how Serilog should behave, including where it should output logs, the minimum level of events to log, and any additional data to include with each log entry.

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "MinimumLevel": "Information",
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "path": "logs/MyAppLog-.txt",
          "rollingInterval": "Day"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "Properties": {
      "Application": "YourAppName"
    }
  }
}

Here’s a breakdown of each section:

Serilog Section

This is the root object for Serilog’s configuration settings within the appsettings.json file, indicating that all configurations within it are meant for Serilog.

Using:

“Using”: [ “Serilog.Sinks.Console”, “Serilog.Sinks.File” ]: This specifies the sinks (or outputs) that Serilog will use. A “sink” is where logs are sent, in this case, to the console and to files. These strings correspond to NuGet packages that need to be included in your project for these sinks to work. We have already added these packages to Step 1.

MinimumLevel:

“MinimumLevel”: “Information”: This sets the minimum log level for events to be written to the configured sinks. Serilog has various log levels (Trace, Debug, Information, Warning, Error, Critical) in ascending order of severity. In this example, it’s set to “Information,” which means that only log events with a level of Information, Warning, Error, or Critical will be logged. Trace and Debug Log Levels events will be ignored.

WriteTo:

This is an array that defines the sinks to which Serilog will write. Each sink can be further configured with its own set of arguments.

"WriteTo": [
  { "Name": "Console" },
  {
    "Name": "File",
    "Args": {
      "path": "logs/MyAppLog-.txt",
      "rollingInterval": "Day"
    }
  }
]

This section configures the sinks. Each sink has a Name, and some sinks have additional Args.

  1. Console: This entry specifies that logs should be written to the console. It doesn’t require any additional arguments.
  2. File: This specifies that logs should also be written to a file. It includes arguments for further configuration:
    • path: Defines the path and file name pattern for the log files. “logs/MyAppLog-.txt” suggests that logs will be written to the logs directory, with the file named starting with MyAppLog-. The is a placeholder for dynamic content, such as date or file number, based on the rolling interval or file size settings.
    • rollingInterval: Specifies how often a new log file should be created. In this case, “Day” means a new file will be created daily. Other options include Hour, Minute, Month, etc.
Enrich:

“Enrich”: [ “FromLogContext”, “WithMachineName”, “WithThreadId” ]: An array of enrichers to add additional information to each log event. Enrichers can add a lot of context to your logs, making them more useful and informative.

  • FromLogContext: Adds properties from the log context to each log event. This is useful for including contextual information that varies with each log event, like HTTP request scope data.
  • WithMachineName: Adds the name of the machine where the log event was generated.
  • WithThreadId: Adds the ID of the thread that generated the log event, which can be helpful for debugging multi-threaded applications.
Properties:

Defines global properties that will be included with every log event, regardless of where it’s generated from within the application.

"Properties": {
  "Application": "YourAppName"
}

In this example, a property named Application is added with a value of YourAppName. This is useful for filtering logs, especially if multiple applications log into the same sink.

What are the options available for rollingInterval in Serilog?

The rollingInterval option in the Serilog file sink configuration controls how frequently a new log file is created. It’s part of the file logging configuration that helps manage the size and organization of log files over time by rotating them based on the specified time period. Here are the options available for rollingInterval:

  • Infinite: No rolling will occur based on time. All log events will be appended to a single file until manually managed or the application configuration changes.
  • Year: Rolls the log file at the start of each calendar year. A new file is started annually, and the year is appended to the file name.
  • Month: Rolls the log file at the start of each calendar month. A new file is started monthly, and the month (and year) is appended to the file name.
  • Day: Rolls the log file at the start of each calendar day. This is useful for systems with moderate to high log volumes and creates a new file daily.
  • Hour: Rolls the log file at the start of each hour. This setting can be useful for systems that generate a lot of logs quickly. It helps keep the file sizes manageable by splitting them hourly.
  • Minute: Rolls the log file every minute. This is the most granular rolling interval and is typically only used in situations where logs are produced at an extremely fast rate, making it necessary to frequently start a new log file to manage the volume of data.

Choosing the right rolling interval depends on the volume of logs your application generates and how you plan to monitor and analyze those logs. More frequent intervals (like Minutes or Hours) are useful for very high-volume environments where logs need to be rotated quickly to avoid large files. Less frequent intervals (like Day, Month, or Year) might suffice for applications with lower log volumes or when log aggregation and analysis tools can efficiently handle larger files.

Step 4: Use Logging in Your Application

With Serilog configured, you can now inject and use the ILogger<T> interface in your controllers or other services to log messages throughout your application to log messages. For a better understanding, please modify the Test Controller as follows:

using Microsoft.AspNetCore.Mvc;

namespace LoggingDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        private readonly ILogger<TestController> _logger;

        public TestController(ILogger<TestController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IActionResult Get()
        {
            _logger.LogTrace("This is a Trace log, the most detailed information.");
            _logger.LogDebug("This is a Debug log, useful for debugging.");
            _logger.LogInformation("This is an Information log, general info about app flow.");
            _logger.LogWarning("This is a Warning log, indicating a potential issue.");
            _logger.LogError("This is an Error log, indicating a failure in the current operation.");
            _logger.LogCritical("This is a Critical log, indicating a serious failure in the application.");

            return Ok("Check your logs to see the different logging levels in action!");
        }
    }
}

Step 5: Run and Test

Run your application and access the above endpoint. You should see logs appearing in your configured sinks, such as the console and log files in the logs directory. In the Console Window, you will see the following:

How to Implement Logging using Serilog in the ASP.NET Core Web API Application with Examples

Now, it should have created the logs folder in your project, and inside the logs folder, you will find two text files. This is because we have configured Serilog in both the Program.cs class file and the appsettings.json file. For the Program.cs class file configuration, it will generate the MyAppLog.txt file, and for the configuration in the appsettings.json file, it will create the MyAppLog-20240320.txt (YYYYMMDD) file as shown in the below image:

How to Implement Logging using Serilog in the ASP.NET Core Web API Application with Examples

Structured Logging in ASP.NET Core Web API using Serilog

Structured logging is a method of logging that focuses on capturing and organizing log data in a consistent format (JSON Format) rather than traditional plain text. Structured logs use a standardized format (typically JSON) to organize the log data, making it easy to query and analyze using log management tools.

In the context of ASP.NET Core Web API, structured logging enables developers to log information in a way that makes it easier to search, analyze, and visualize log data. This can significantly improve monitoring, debugging, and troubleshooting issues. This approach provides significant advantages over traditional logging methods, particularly when dealing with complex or distributed systems.

Example to Understand Structured Logging Using Serilog in ASP.NET Core Web API

Let us see an example of implementing structured logging using Serilog in the ASP.NET Core Web API application. We will create a simple application that logs various types of structured log messages.

Create a Model and Controller

Let us assume we are building a simple API to manage books in a library. First, define a Book model. Add a folder named Models and then add a class file named Book.cs within the Models folder. Copy and paste the following code.

namespace LoggingDemo.Models
{
    public class Book
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public int YearPublished { get; set; }
    }
}

Next, create an API Empty Controller named BooksController within the Controllers folder and then copy and paste the following code, which adds actions to add and retrieve books. Here, we will log structured data about the operations being performed:

using LoggingDemo.Models;
using Microsoft.AspNetCore.Mvc;

namespace LoggingDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        private static readonly List<Book> Books = new List<Book>()
        {
            new Book(){Id = 1001, Title = "ASP.NET Core", Author = "Pranaya", YearPublished = 2019},
            new Book(){Id = 1001, Title = "SQL Server", Author = "Pranaya", YearPublished = 2022}
        };
        private readonly ILogger<BooksController> _logger;

        public BooksController(ILogger<BooksController> logger)
        {
            _logger = logger;
        }

        [HttpPost]
        public IActionResult AddBook([FromBody] Book book)
        {
            Books.Add(book);

            //Structured Logging, i.e., JSON Format
            _logger.LogInformation("Added a new book {@Book}", book);
            return Ok();
        }

        [HttpGet]
        public IActionResult GetBooks()
        {
            //Structured Logging, i.e., JSON Format
            _logger.LogInformation("Retrieved all books. Books: {@Books}", Books);
            return Ok(Books);
        }
    }
}

In the above controller, the AddBook action logs the entire book object as structured data using the @ operator, which tells Serilog to treat the book object as structured data rather than converting it to a string. The GetBooks action logs all the books as structured data using the @ operator.

Centralizing the Serilog Configuration in AppSettings.JSON File:

If you prefer centralizing your Serilog configuration within the appsettings.json file instead of having it partially in the Program.cs file. You can achieve this by utilizing Serilog.Settings.Configuration package. This approach simplifies maintenance and modifications to your logging setup without recompiling your application.

Configure Serilog Entirely in appsettings.json

In your appsettings.json, define the Serilog configuration. You can specify sinks, filters, minimum log levels, etc. Here is an example that includes console and file sinks:

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Error"
      }
    },
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "path": "logs/MyAppLog-.txt",
          "rollingInterval": "Day",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName" ],
    "Properties": {
      "Application": "LoggingDemo"
    }
  }
}
Understanding the above Modified Code:
MinimumLevel
  • Default: Specifies the minimum log level that will be captured globally. Here, it’s set to “Information”, meaning that logs of Information level and higher (Warning, Error, Critical) will be recorded, while Debug and Trace level logs will be ignored.
  • Override: Allows specifying different minimum log levels for specific namespaces.
    • “Microsoft” is set to “Warning”, meaning log events from Microsoft’s libraries will only be recorded at Warning level and above, ignoring Information and lower levels.
    • “System” is set to “Error”, so only Error and Critical log levels from System namespaces will be recorded. This reduces the logs from these sources.
WriteTo

This section configures the outputs (sinks) where the logs should be written.

  • A console sink is added to write logs to the console window.
  • A File sink is also specified with several arguments:
    • path: “logs/MyAppLog-.txt” sets the directory and naming convention for the log files. Serilog automatically creates and writes to these files.
    • rollingInterval: “Day” indicates that Serilog will create a new log file every day to prevent a single file from becoming too large and to facilitate easier log management over time.
    • outputTemplate: Defines the format of each log entry. {Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception} specifies that each log should start with a timestamp in a specific format, followed by the log level (three-letter abbreviation), the log message, and finally, the exception details if an exception is being logged. lj stands for “literal JSON”, ensuring that structured data is logged as JSON literals.
Enrich

Specifies additional data to include with each log entry:

  • “FromLogContext” adds contextual information to the logs, which is useful for correlating logs with specific operations or requests.
  • “WithMachineName” includes the name of the machine where the log entry was generated, which is helpful in environments with multiple servers.
Properties

Defines static properties to be included with every log entry:

  • “Application”: “LoggingDemo” adds an Application property with the value “LoggingDemo” to each log entry, which can be useful for filtering logs, especially when logs from multiple applications are aggregated in a central location.
Initialize Serilog in Program.cs

In your Program.cs file, instead of configuring Serilog directly with code, you’ll load the Serilog configuration from the appsettings.json file. You don’t need to explicitly set up the logger with sinks or filters here, as those are now managed in your configuration file:

//Namespace
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Initialize Serilog from appsettings.json
builder.Host.UseSerilog((context, services, configuration) => configuration
    .ReadFrom.Configuration(context.Configuration)
    .ReadFrom.Services(services)
    .Enrich.FromLogContext());

The above code snippet instructs Serilog to read its configuration from the app’s configuration system, which includes appsettings.json and any other configured sources. The UseSerilog method sets up Serilog as the logging provider. Here is the Code Explanation:

builder.Host.UseSerilog(…): This line instructs the application host to use Serilog as its logging framework. It replaces the default logger with Serilog, enabling it to capture logs throughout the application.

(context, services, configuration) => …: The UseSerilog method takes a delegate (a lambda expression in this case) with three parameters: context, services, and configuration to configure Serilog.

  • context: This parameter represents the WebHostBuilderContext, which contains information about the application’s hosting environment, including configuration and environment data. It’s useful for making decisions based on the environment (Development, Production, etc.) and for accessing configuration settings.
  • services: This is an IServiceProvider that gives access to the application’s service container, allowing Serilog to resolve services that it might need for its configuration. 
  • configuration: This is an instance of LoggerConfiguration, a Serilog object used to build and configure the logger. It’s where you define how Serilog should behave, including what sinks to use, minimum logging levels, enrichers, etc.
Configuration Methods

The lambda function then chains several methods to configure Serilog:

  • .ReadFrom.Configuration(context.Configuration): This tells Serilog to read its configuration from the application’s settings, typically found in appsettings.json (or appsettings.{Environment}.json) or other configuration sources defined in the application. It enables easy customization of Serilog’s behavior (like minimum logging levels, output destinations, etc.) without changing the code by modifying configuration files.
  • .ReadFrom.Services(services): This line instructs Serilog to look for configuration components, like enrichers or sinks, that might have been registered in the application’s service container. This is a powerful feature that allows for more dynamic configurations based on services.
  • .Enrich.FromLogContext(): Adds additional contextual information to each log event. This is very useful for web applications, as it allows you to include details such as the Request ID in logs, making it easier to correlate logs with specific HTTP requests.

With these changes, Serilog is now fully configured through appsettings.json, and your Program.cs does not contain any explicit Serilog configuration logic beyond initializing it to read from the configuration file. Run your application to verify that logging works as expected.

Testing and Observing Structured Logs

Run your application and use a tool like Postman or Fiddler to test the API endpoints. For example, to add a new book, you could POST to https://localhost:7223/api/books with a JSON body:

{
    "id": 1003,
    "title": "C#.NET",
    "author": "Pranaya",
    "yearPublished": 2023
}

Once you access the endpoint with the above request body, you can verify the Console window, and it should display the following message:

Centralizing the Serilog Configuration in AppSettings.JSON File

Now, if you open the MyAppLog-20240320 txt file, then you will also see the same log as shown in the below image:

Centralizing the Serilog Configuration in AppSettings.JSON File

Similarly, you can also check the other GET Endpoint and observe the logs. Now, if you observe one thing, in the appsettings file, we have specified the following Enrich and Properties, but these are not printing in the logs.

"Enrich": [ "FromLogContext", "WithMachineName" ],
"Properties": {
  "Application": "LoggingDemo"
}

This is because the exact format of the log entries will depend on your configured output template in Serilog. If you haven’t specified an output template in your appsettings.json, Serilog uses its default format, and currently, we are using the following template, which does not use the Enrich and Properties.

“outputTemplate”: “{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}”

To see the enrichments (MachineName, ThreadId) and properties (ApplicationName, Environment) in action, ensure your log events include these in their messages. You can customize the output template to include these properties explicitly, as follows:

“outputTemplate”: “{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{MachineName}] [{Properties}] {Message:lj}{NewLine}{Exception}”

Note: You can also remove the Enrich and Properties settings from the appsettings.json file, and it should work as expected, as they are optional.

When Should We Use Serilog in ASP.NET Core Web API?

Deciding when to use Serilog in your ASP.NET Core Web API projects involves evaluating your logging requirements and the specific features that Serilog offers. Here are some scenarios where Serilog might be particularly beneficial:

  • Need for Structured Logging: If you require structured logging to query and analyze your logs easily. Structured logs are particularly useful for complex applications where understanding the context of logs is crucial for debugging and monitoring.
  • Integration with Log Management Systems: When you plan to use or already use log management systems like ELK (Elasticsearch, Logstash, Kibana), Seq, or Splunk. Serilog’s structured logs are highly compatible with these systems, making searching and visualizing log data easier.
  • Complex Logging Requirements: For applications with complex logging requirements, such as needing to log to multiple destinations (files, databases, cloud services) or requiring detailed control over what gets logged and how. Serilog’s extensive range of sinks and filtering capabilities make it a strong candidate.
  • Performance Considerations: When performance is a concern, but logging is essential. Serilog has been designed to minimize its impact on application performance, offering features like asynchronous logging and batching.
  • Rich Log Contexts: If you want to enrich your logs with additional contextual information without cluttering your logging calls. Serilog allows for easy log enrichment with application-wide properties, such as user IDs, session IDs, or operation IDs, improving the diagnostic capabilities of your logs.
  • High-Level Customization: When you require a high level of customization in your logging setup. Serilog offers a plethora of enrichers, filters, and output formats, allowing for a tailored logging setup that matches your application’s specific needs.
When Might You Not Use Serilog?

While Serilog is a powerful tool, it might not always fit best. Consider alternatives if:

  • Your logging needs are very basic, and the built-in logging frameworks of ASP.NET Core suffice.
  • You are working on a very small project with limited resources and want to avoid the overhead of learning and configuring a new logging framework.
  • You have stringent performance requirements and need to minimize every possible overhead, although, with proper configuration, Serilog’s performance impact can be minimized.

Different Srinks Available with Serilog in ASP.NET Core

Serilog is a popular logging library for .NET applications, known for its flexibility and easy integration with various logging destinations or “sinks”. In the context of ASP.NET Core applications, Serilog provides a range of sinks that allow you to log into different storage systems, formats, or services. Here’s a brief overview of some of the different sinks available:

  • Console Sink: This writes log events to the console. It is useful for development environments where you want to see live logging output.
  • File Sink: Logs events to local or network disk files. This sink can be configured to create new files based on time or size constraints.
  • Seq Sink: Targets the Seq log server, which is designed for structured logging. Seq provides a rich query interface and can aggregate logs from multiple sources.
  • Elasticsearch Sink: Enables logging to Elasticsearch, facilitating full-text search and visualization of logs with tools like Kibana.
  • Rolling File Sink: An extension of the File Sink that adds the capability to automatically roll files over a period of time or size limit, making log management easier.
  • Application Insights Sink: This integrates with Azure’s Application Insights, allowing detailed telemetry and log data to be sent to Azure for analysis and monitoring.
  • Splunk Sink: Forwards log events to Splunk, a platform for searching, monitoring, and analyzing machine-generated big data.
  • AWS CloudWatch Sink: This sink logs directly to AWS CloudWatch, which can monitor logs and trigger alerts based on log data.
  • GCP Stackdriver Sink: Targets Google Cloud’s Stackdriver Logging, enabling logging in Google Cloud environments.
  • Raygun Sink: Sends log data to Raygun, a service that provides error and performance monitoring.
  • MS SQL Server Sink: Logs events to a Microsoft SQL Server database, allowing for persistence and query capabilities within an RDBMS.
  • PostgreSQL Sink: Similar to the MS SQL Server Sink, but for logging directly to PostgreSQL databases.
  • LiteDB Sink: Logs to a LiteDB file database, a lightweight, serverless NoSQL database perfect for simpler applications or lower resource environments.
  • RabbitMQ Sink: Enables logging through RabbitMQ, a message broker, allowing log messages to be queued and processed asynchronously.
  • Kafka Sink: Publishes log events to a Kafka topic, which can be useful in distributed systems for logging across multiple services and instances.

These sinks can be used individually or in combination, depending on the needs of your application and the environment in which it runs. To use these sinks, you typically install the corresponding NuGet package for the sink you want to use and configure it in your application’s startup code.

In the next article, I will discuss Logging into a SQL Server Database using Entity Framework Core with Serilog in ASP.NET Core Web API Application with Examples. In this article, I explain How to Implement Logging Using Serilog in ASP.NET Core Web API Application with Examples. I hope you enjoy this article, How to Implement Logging Using Serilog in ASP.NET Core Web API.

Leave a Reply

Your email address will not be published. Required fields are marked *