How To Write Logs To Amazon CloudWatch Using Serilog In .NET 6 Web API

Introduction

In this article, you will learn how to write logs to Amazon CloudWatch using Serilog in .NET 6 Web API.

Topics Covered

This article demonstrates how to build the following:

  • Create a sample ASP.NET Core Web API    
  • Testing
  • Clean up resources

Pre-requisites

  1. Download and install Visual Studio 2022.
  2. Download and install AWS Toolkit for Visual Studio 2022.
  3. An Active AWS Account. (See AWS Account Page.)
  4. User with sufficient access to create AWS resources for this article.(See IAM role in AWS IAM Roles Documentation.)
  5. User should have programmatic access keys.(See IAM user and Access in the AWS IAM documentation.)
  6. Download and install Amazon command line interface (AWS CLI). Configure AWS CLI.

Tools

  1. AWS Console
  2. Visual Studio 2022

Task 1 - Create a sample ASP.NET Core Web API

In this task, you will see how to create a new sample .NET 6 ASP.NET Core Web API using Visual Studio 2022.

Step 1 - Open Visual Studio 2022, click Create a new project.

Step 2 - Search ASP.NET in the search bar, select ASP.NET Core Web API project template and click Next.

Step 3 - Enter the project name as AWSSeriLogNetAPIDemo. Click Next.

Step 4 - Select .NET 6.0 (Long-term support) as Framework. Click Create.

Step 5 - Add AWS.Logger.SeriLog NuGet package.

Step 6 - Open Program.cs file and replace the code as shown below.

using AWS.Logger;
using AWS.Logger.SeriLog;
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

AWSLoggerConfig configuration = new AWSLoggerConfig("Serilog.DemoLogGroup");
configuration.Region = "us-west-2";

var logger = new LoggerConfiguration()
.WriteTo.AWSSeriLog(configuration)
.CreateLogger();

builder.Services.AddSingleton<Serilog.ILogger>(logger);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

NOTE: Hard-coded values are used only for testing purpose.

Step 7 - Open WeatherForecastController.cs file and add the logging code as shown below.

using Microsoft.AspNetCore.Mvc;

namespace AWSSeriLogNetAPIDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly Serilog.ILogger _logger;

        public WeatherForecastController(Serilog.ILogger logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            _logger.Information("Log entered from WeatherForecast controller");
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

Task 2 - Testing

In this task, you will see how to test the API to write logs to Amazon CloudWatch.

Step 1 - Hit F5 to run the API locally and Swagger will be displayed. Expand /WeatherForecast and click Try it out. Click Execute to get the response.

Step 2 - Open AWS Console, select the region (mentioned in the code) and navigate to Amazon CloudWatch service. In the left navigation, click expand Logs -> Log Groups. You can see the newly created log group and logs as shown below.

Task 3 - Clean up resources

Delete all the resources to ensure that you're not charged for any services you aren't using.

Summary

This article describes how to write logs to Amazon CloudWatch using Serilog in .NET 6 Web API.


Recommended Free Ebook
Similar Articles