Configure logging for .NET applications in Amazon CloudWatch Logs by using NLog - AWS Prescriptive Guidance
Services or capabilities described in AWS documentation might vary by Region. To see the differences applicable to the AWS European Sovereign Cloud Region, see the AWS European Sovereign Cloud User Guide.

Configure logging for .NET applications in Amazon CloudWatch Logs by using NLog

Bibhuti Sahu and Rob Hill (AWS), Amazon Web Services

Summary

This pattern describes how to use the NLog open-source logging framework to send .NET application logs and events to Amazon CloudWatch Logs. In the Amazon CloudWatch console, you can view log messages in near real time, create metric filters, and configure alarms that notify you when a threshold is breached. With Amazon CloudWatch Application Insights, you can use automated or custom dashboards to help identify problems in your applications and infrastructure.

To write log messages to CloudWatch Logs, you add the AWS.Logger.NLog NuGet package to your .NET project and configure CloudWatch Logs as an NLog target. The application authenticates by using temporary credentials from an AWS Identity and Access Management (IAM) role instead of long-term access keys. A retention policy and encryption with AWS Key Management Service (AWS KMS) help protect the log group.

Prerequisites and limitations

Prerequisites

Limitations

  • You configure retention, encryption, and data protection settings on the log group, not through the NLog configuration.

  • CloudWatch Logs service quotas apply, such as the PutLogEvents API batch size and request rate. AWS.Logger.NLog automatically batches and retries requests.

  • Some AWS services aren’t available in all AWS Regions. For Region availability, see AWS Services by Region.

Product versions

  • .NET 10 (LTS)

  • .NET Framework 4.8 or 4.8.1 (Windows)

  • AWS.Logger.NLog 5.0.1 or later, and NLog 5.x or later

  • AWS Tools for PowerShell V5 (optional, for the setup commands)

  • Visual Studio 2022 or later, or the .NET CLI

Architecture

Target technology stack  

  • NLog with the AWS.Logger.NLog target

  • Amazon CloudWatch Logs, encrypted with AWS KMS

  • IAM role that provides temporary credentials

Target architecture

Architecture diagram of NLog writing log data for a .NET application to Amazon CloudWatch Logs.
  1. The .NET application writes log events to the NLog framework.

  2. The AWS.Logger.NLog target gets temporary credentials from the IAM role attached to the compute environment, through the AWS SDK for .NET default credential chain.

  3. The target sends batched log events to a CloudWatch Logs log group that uses AWS KMS encryption.

  4. You use metric filters, alarms, CloudWatch Logs Insights, and dashboards to monitor the application.

Tools

AWS services

Other tools

  • AWS.Logger.NLog is an NLog target that records log data to CloudWatch Logs.

  • NLog is an open-source logging framework for .NET platforms that helps you write log data to targets such as databases, log files, or consoles.

  • PowerShell is a Microsoft automation and configuration management program that runs on Windows, Linux, and macOS.

  • Visual Studio is an integrated development environment (IDE) that includes compilers, code completion tools, graphical designers, and other features that support software development.

Best practices

  • Use temporary credentials. Attach an IAM role to the compute resource. Don’t embed access keys in code or in NLog.config. For more information, see Security best practices in IAM.

  • Apply least privilege. Grant only the write actions that the logger needs, scoped to the Amazon Resource Name (ARN) of the specific log group.

  • Set a retention policy. By default, CloudWatch Logs keeps log data indefinitely. Set retention on the log group, outside of the NLog configuration.

  • Encrypt log data. Associate an AWS KMS customer managed key with the log group. For more information, see Encrypt log data in CloudWatch Logs using AWS KMS.

  • Protect sensitive data. Don’t log secrets, tokens, or personal data. Add a data protection policy to detect and mask sensitive data.

  • Use private connectivity. For workloads in private subnets, use an interface endpoint in Amazon Virtual Private Cloud (Amazon VPC) for CloudWatch Logs (com.amazonaws.<region>.logs).

  • Set log levels for production. Set the minimum log level to Info or higher in production to help control cost and reduce noise.

Epics

TaskDescriptionSkills required

Create the log group and IAM policy.

Create the log group in advance so that you can apply retention and encryption and scope IAM permissions to it. Use AWS Tools for PowerShell to run the following commands:

New-CWLLogGroup -LogGroupName "NLog.TestGroup" ` -KmsKeyId "arn:aws:kms:<region>:111122223333:key/<key-id>" Write-CWLRetentionPolicy -LogGroupName "NLog.TestGroup" -RetentionInDays 90

Then follow the instructions in Create IAM policies (console). Use the least-privilege policy in the Additional information section. It allows only the write actions that the logger needs, on the specific log group.

AWS administrator, AWS DevOps

Create an IAM role for the compute environment.

Follow the instructions in Create a role to delegate permissions to an AWS service. Choose the service that runs your application (for example, Amazon EC2 or an Amazon Elastic Container Service (Amazon ECS) task), and attach the policy that you created. The application’s compute resource, not CloudWatch Logs, assumes this role. A sample trust policy is in the Additional information section.

AWS administrator, AWS DevOps

Attach the role to the application.

  • For Amazon EC2, attach the role as an instance profile.

  • For Amazon ECS, set the role as the task role in the task definition.

  • For Amazon Elastic Kubernetes Service (Amazon EKS), use Amazon EKS Pod Identity or IAM roles for service accounts (IRSA).

  • For AWS Lambda, use the function’s execution role.

  • For on-premises servers, use AWS Identity and Access Management Roles Anywhere.

  • (Local development only) Install AWS Tools for PowerShell, and sign in with IAM Identity Center to get short-term credentials. Don’t store long-term access keys. For more information, see Configure tool authentication.

AWS administrator, AWS DevOps
TaskDescriptionSkills required

Install the NuGet package.

From the project directory, run the following command:

dotnet add package AWS.Logger.NLog --version 5.0.1

Alternatively, in the Visual Studio Package Manager Console (Tools, NuGet Package Manager, Package Manager Console), run the following command:

Install-Package AWS.Logger.NLog -Version 5.0.1
App developer

Configure the logging target.

  • Open the NLog.config file (or the NLog section of appsettings.json).

  • For the target type, enter AWSTarget.

  • For logGroup, enter the name of the log group that you created.

  • For region, enter the AWS Region of the log group.

  • When the application runs on AWS, don’t set a profile, access key, or secret key. The target uses the IAM role automatically.

For sample configurations, see the Additional information section. When you run your application, NLog writes the log messages and sends them to CloudWatch Logs.

App developer
TaskDescriptionSkills required

Validate logging.

Run the application, and then follow the instructions in Working with log groups and log streams to view log events for the .NET application. If no events appear, see the Troubleshooting section.

General AWS

Monitor the .NET application stack.

Use CloudWatch Logs Insights, CloudWatch Metrics Insights, and CloudWatch Application Insights to monitor your .NET workload. Configure alarms to receive alerts, and create a dashboard to view your key metrics and logs in one place.

(Optional) To mask personal data and credentials, add a data protection policy to the log group. For instructions, see Help protect sensitive log data with masking.

General AWS

Troubleshooting

IssueSolution

Log data doesn’t appear in CloudWatch Logs.

Confirm that the IAM policy is attached to the role that the application’s compute resource uses (instance profile, task role, or execution role), and that the logGroup and region values in NLog.config match the log group.

AccessDeniedException appears in the NLog internal log.

Check that the Amazon Resource Name (ARN) in the Resource element of the IAM policy matches the log group name, Region, and account. If the log group is encrypted, check that the AWS KMS key policy allows the CloudWatch Logs service principal for that Region (logs.<region>.amazonaws.com).

The application can’t find AWS credentials.

When running on AWS, verify that the IAM role is attached to the compute resource (instance profile, task role, or execution role). For local development, sign in again with IAM Identity Center to refresh the session. Don’t use long-term access keys as a workaround.

The application writes logs to an unexpected AWS Region.

Set the AWS_REGION environment variable for the application, or add the region attribute to the AWSTarget. If neither is set, the AWS SDK for .NET uses the Region from the shared config profile or from Amazon EC2 instance metadata.

You need to diagnose NLog target errors.

On the nlog element, set internalLogLevel="Warn" and internalLogFile to a file path. Then review the file for exceptions from the AWS target. Turn off internal logging after you finish troubleshooting.

Related resources

Additional information

Least-privilege IAM policy

Replace the Region, account ID, and log group name with your own values. If you create the log group in advance (recommended), you can remove logs:CreateLogGroup.

{ "Version": "2012-10-17", "Statement": [ { "Sid": "WriteAppLogs", "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents", "logs:DescribeLogStreams" ], "Resource": [ "arn:aws:logs:<region>:111122223333:log-group:NLog.TestGroup", "arn:aws:logs:<region>:111122223333:log-group:NLog.TestGroup:log-stream:*" ] }, { "Sid": "DescribeGroups", "Effect": "Allow", "Action": "logs:DescribeLogGroups", "Resource": "arn:aws:logs:<region>:111122223333:log-group:*" } ] }

Sample trust policy (Amazon EC2)

For Amazon ECS, use ecs-tasks.amazonaws.com. For AWS Lambda, use lambda.amazonaws.com.

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }

Sample NLog.config (.NET 10)

<?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" internalLogLevel="Warn" internalLogFile="logs/nlog-internal.log"> <extensions> <add assembly="NLog.AWS.Logger" /> </extensions> <targets> <target name="aws" type="AWSTarget" logGroup="NLog.TestGroup" /> </targets> <rules> <logger name="*" minlevel="Info" writeTo="aws" /> </rules> </nlog>

Sample app.config (.NET Framework 4.8)

<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" /> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" /> </startup> <nlog> <extensions> <add assembly="NLog.AWS.Logger" /> </extensions> <targets> <target name="aws" type="AWSTarget" logGroup="NLog.TestGroup" /> </targets> <rules> <logger name="*" minlevel="Info" writeTo="aws" /> </rules> </nlog> </configuration>

This sample omits the region attribute so that the AWS SDK for .NET resolves the Region from the environment: the AWS_REGION environment variable, the shared config profile, or Amazon EC2 instance or Amazon ECS task metadata. To set it explicitly, add region="<your-aws-region>" to the target. Replace <region> and the account ID in the Amazon Resource Names (ARNs) in the IAM policy with your own values.