Introduction
Logging is a very critical and essential part of any software. It helps us to create information, Errors, and other type of logs to investigate the essence of problems. .NET Core web API has built-in support for logging APIs and can work with various logging providers. Using NLog, we can send application logs to one or more destinations and learn how to implement NLog with ASP.NET Core web API.
NLog is an open-source and flexible framework that works with various .NET platforms. In this article, we will use .Net core. NLog is easy to use and extend. Also, it provides more flexibility in terms of configuration. We can also change the logging configuration on-the-fly. The target is used to store, display, and pass the log messages to the provided destination. NLog can write a log to one or more targets simultaneously. NLog provides more than 30 targets, including file, event log, database, email, console, and AWS.
This article will configure logs in the file and AWS cloud watch.
Topics Covered
This article demonstrates how to build the following,
- Create a sample ASP.NET Core Web API.
- Configure NLog in ASP.NET Core Web API.
- Testing
- Modify the NLog configuration file and make it compatible for AWS Cloud Watch.
- Clean up resources.
Pre-requisites
- Download and install Visual Studio 2022.
- Download and install AWS Toolkit for Visual Studio 2022.
- An Active AWS Account. (See AWS Account Page.)
- User with sufficient access to create AWS resources for this article. (See IAM role/Server Permission in AWS IAM Roles Documentation.)
- The user should have programmatic access keys. (See IAM user and Access in the AWS IAM documentation.)
- Download and install the Amazon command line interface (AWS CLI). Configure AWS CLI.
Tools
- AWS Console
- Visual Studio 2022
Task 1. Create a sample ASP.NET Core Web API
This task will show you how to create a new sample .NET ASP.NET Core Web API using Visual Studio 2022.
Step 1
Open Visual Studio 2022 and 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 NLogWithCloudWatch Next.
Step 4
Select .NET Core as Framework. Click Create.
Step 5
Expand the Controller folder in the solution explorer, right-click WeatherForecastController.cs file, and click Delete. Right-click WeatherForecast.cs file and click Delete.
Step 6
Right-click the Controllers folder, click Add,, and then click Controller.
Step 7
Select API -> API Controller with read/write actions. Click Add.
Step 8
Leave the default name and click Add.
Task 2. Configure NLog in ASP.NET Core Web API
Step 1. Add AWS.Logger.NLog NuGet package.
Step 2. Modify the class with the name "Program".
Consider the namespaces.
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;
Open Program.cs file and add the following code snippet as shown below. We are modifying the IWebHostBuilder and configuring NLog as a default logger.
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;
namespace NLogWithCloudWatch
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
})
.UseNLog();
}
}
Step 3.
1. Add dependency in csproj manually or using NuGet
Install the latest:
In csproj:
<PackageReference Include="NLog.Web.AspNetCore" Version="4.*" />
<PackageReference Include="NLog" Version="4.*" />
2. Create a nlog.config file.
Create a nlog.config (lowercase all) file in the root of your project.
We use this example:
<?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"
autoReload="true"
throwConfigExceptions="true"
internalLogLevel="info"
internalLogFile="c:\temp\internal-nlog-AspNetCore3.txt">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<!-- File Target for all log messages with basic details -->
<target xsi:type="File" name="allfile" fileName="c:\temp\nlog-AspNetCore3-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="NLogWithCloudWatch.*" minlevel="info" writeTo="allfile" />
</rules>
</nlog>
NOTE
<logger name="NLogWithCloudWatch.*" minlevel="info" writeTo="allfile" />
Mention the file name, and using this name file name NLog will create a file in the respective location.
fileName="c:\temp\nlog-AspNetCore3-all-${shortdate}.log"
Specify the file location where this file will create.
3. Enable copy to the bin folder
Enable copy to bin folder for nlog.config
or edit .csproj
file manually and add:
<ItemGroup>
<Content Update="nlog.config" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
4. Configure appsettings.json
The Logging configuration specified in appsettings.json
overrides any call to SetMinimumLevel
. So, either remove "Default":
or adjust it correctly to your needs.
{
"Logging": {
"LogLevel": {
"Default": "Trace",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Remember also to update any environment specific configuration to avoid any surprises. Ex appsettings.Development.json
Step 4. Open LoggerController.cs file and replace the code with the following as shown below.
Task 3. Testing
In this task, you will see how to test the API to generate the logs in the respective file.
Hit F5 to run the API locally, and Swagger will be displayed. Expand /api/values and click Try it out. Click Execute to get the response as shown below.
File Created with the specified name, and when we open it, below mentioned logs are there.
Task 4. Modify the NLog configuration file and make it compatible for AWS Cloud Watch
To create the logs on the AWS cloud, we have to modify the nlog.configuration file.
This file exists in the project root folder, and we must modify the code as mentioned below.
Step 1. Add another extension
<extensions> <add assembly="NLog.AWS.Logger" /> </extensions>
Step 2. Add another target.
<target name="aws" type="AWSTarget" logGroup="Application-Dev-Log" region="us-east-1" />
Step 3. Another logger location
<logger name="NLogWithCloudWatch.*" minlevel="Trace" writeto="aws" />
Target will inform NLog that the type is "AWS" and the cloud watch log group name is this. In my case, it is "Application-Dev-Log". It might be different in your case, and last, we have to specify the region "us-east-1". It will be different based on your location.
The logger will talk to NLog and inform that the write location is "AWS" now.
Note:
If you want to run the program locally, then either your project needs AWS permission using AWS Tool else you have to comment these lines and use without AWS configuration nlog configuration file.
Task 4. Clean up resources
Delete all the resources to ensure you're not charged for any services you aren't using.