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
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)
Prerequisites and limitations
Prerequisites
An active AWS account.
A .NET web or console application that targets a supported .NET version (see Product versions) and uses NLog for application logging.
Permissions to create IAM policies and roles, and to pass a role to an AWS service. For more information, see Create a role to delegate permissions to an AWS service
and Grant a user permissions to pass a role to an AWS service . A compute environment that can use an IAM role, such as Amazon Elastic Compute Cloud (Amazon EC2)
, Amazon Elastic Container Service (Amazon ECS) , Amazon Elastic Kubernetes Service (Amazon EKS) , AWS Lambda , or AWS Elastic Beanstalk . For on-premises servers, use AWS Identity and Access Management Roles Anywhere. For local development, use an AWS IAM Identity Center user. (Optional) An AWS KMS customer managed key for log group encryption.
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
PutLogEventsAPI 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

The .NET application writes log events to the NLog framework.
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.
The target sends batched log events to a CloudWatch Logs log group that uses AWS KMS encryption.
You use metric filters, alarms, CloudWatch Logs Insights, and dashboards to monitor the application.
Tools
AWS services
Amazon CloudWatch Application Insights
helps you observe the health of your applications and underlying AWS resources. Amazon CloudWatch Logs
helps you centralize the logs from all your systems, applications, and AWS services so you can monitor them and archive them securely. AWS Identity and Access Management (IAM)
helps you securely manage access to your AWS resources by controlling who is authenticated and authorized to use them. AWS Key Management Service (AWS KMS)
helps you create and control cryptographic keys to help protect your data. AWS Tools for PowerShell
are a set of PowerShell modules that help you script operations on your AWS resources from the PowerShell command line.
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
| Task | Description | Skills 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
Then follow the instructions in Create IAM policies (console) | 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 | AWS administrator, AWS DevOps |
Attach the role to the application. |
| AWS administrator, AWS DevOps |
| Task | Description | Skills required |
|---|---|---|
Install the NuGet package. | From the project directory, run the following command:
Alternatively, in the Visual Studio Package Manager Console (Tools, NuGet Package Manager, Package Manager Console), run the following command:
| App developer |
Configure the logging target. |
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 |
| Task | Description | Skills required |
|---|---|---|
Validate logging. | Run the application, and then follow the instructions in Working with log groups and log streams | General AWS |
Monitor the .NET application stack. | Use CloudWatch Logs Insights (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
| Issue | Solution |
|---|---|
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 |
AccessDeniedException appears in the NLog internal log. | Check that the Amazon Resource Name (ARN) in the |
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 |
You need to diagnose NLog target errors. | On the |
Related resources
Working with log groups and log streams
(CloudWatch Logs documentation) Encrypt log data in CloudWatch Logs using AWS KMS
(CloudWatch Logs documentation) Security best practices in IAM
(IAM documentation) Amazon CloudWatch Logs and .NET Logging Frameworks
(AWS blog post)
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.