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

Introduction

In this article, you will learn how to write logs to Amazon CloudWatch using NLog 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

Prerequisites

  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 AWSNLogNetAPIDemo. Click Next.

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

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

Step 6 - Right click the project and add config file named as NLog.config. Update the config file with the following configuration.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      throwConfigExceptions="true">
	<extensions>
		<add assembly="NLog.AWS.Logger" />
	</extensions>
	<targets>
		<target name="aws" type="AWSTarget" logGroup="NLogDemo" region="us-west-2"/>
		<target name="logfile" xsi:type="Console" layout="${callsite} ${message}" />
	</targets>
	<rules>
		<logger name="*" minlevel="Info" writeTo="logfile,aws" />
	</rules>
</nlog>

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

using Microsoft.AspNetCore.Mvc;
using NLog;

namespace AWSNLogNetAPIDemo.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 Logger logger;

        public WeatherForecastController()
        {
            logger = LogManager.GetCurrentClassLogger();
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            logger.Info("Logged from GetWeatherForecast API");
            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 NLog.config) 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 NLog in .NET 6 Web API.

Recommended Ebook

Printing in C# Made Easy

Download Now!
Similar Articles