AWS.Logger.NLog 3.3.4

Prefix Reserved
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package AWS.Logger.NLog --version 3.3.4                
NuGet\Install-Package AWS.Logger.NLog -Version 3.3.4                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="AWS.Logger.NLog" Version="3.3.4" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add AWS.Logger.NLog --version 3.3.4                
#r "nuget: AWS.Logger.NLog, 3.3.4"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install AWS.Logger.NLog as a Cake Addin
#addin nuget:?package=AWS.Logger.NLog&version=3.3.4

// Install AWS.Logger.NLog as a Cake Tool
#tool nuget:?package=AWS.Logger.NLog&version=3.3.4                

AWS Logging .NET

This repository contains plugins for popular .NET logging frameworks that integrate with Amazon Web Services. The plugins use the Amazon CloudWatch Logs service to write log data to a configured log group. The logs can be viewed and searched using the AWS CloudWatch Console.

For a history of releases view the release change log

AWS Lambda

These packages batch logging messages in a queue and send messages to CloudWatch Logs using a background thread. The use of the background thread means that the messages are not guaranteed to be delivered when used in AWS Lambda. The reason is because the background thread will be frozen once a Lambda event is processed and may not ever be unfrozen if more Lambda events are not received for some time.

When using Lambda it is recommended to use either the ILambdaContext.Logger.LogLine or the Amazon.Lambda.Logging.AspNetCore package.

Required IAM Permissions

Regardless of the framework used, the following permissions must be allowed (via IAM) for the provided AWS credentials.

logs:CreateLogGroup
logs:CreateLogStream
logs:PutLogEvents
logs:DescribeLogGroups

The practice of granting least privilege access is recommended when setting up credentials. You can further reduce access by limiting permission scope to specific resources (such as a Log Stream) by referencing its ARN during policy creation.

For more information and a sample JSON policy template, please see Amazon CloudWatch Logs and .NET Logging Frameworks on the AWS Developer Blog.

Optional IAM Permissions

The following IAM permissions are optional depending on the configured features of the logger.

Feature IAM Permission(s) for feature Configuration Setting
Set new log group retention policy logs:PutRetentionPolicy NewLogGroupRetentionInDays

Configuring the Log Stream Name

Prior to the versions listed below, these libraries followed CloudWatch Logs' best practice of having the log stream name be generated. The name could be customized by adding a suffix or prefix using the LogStreamNameSuffix and LogStreamNamePrefix configuration properties.

Generating the name ensured that each process within an application has its own log stream to write to. Otherwise when one process writes to the same stream, the sequenceToken maintained within the process goes out of sync. This generated errors and retries causing performance issues.

In 2023 CloudWatch Logs removed the SequenceToken requirement, which removes the need to split log ingestion across multiple log streams and coordinate the sequence token across multiple clients.

The following versions introduce a new LogStreamName setting, which can be used to specify the full log stream name. When this is set LogStreamNamePrefix and LogStreamNameSuffix will be ignored.

  1. AWS.Logger.Nlog - 3.3.0
  2. AWS.Logger.Log4net - 3.5.0
  3. AWS.Logger.AspNetCore - 3.5.0
  4. AWS.Logger.SeriLog - 3.4.0

Setting new Log Group Retention Policy

These libraries support setting a log retention policy on any CloudWatch Log Groups which they create. This feature is enabled using the NewLogGroupRetentionInDays configuration property. The DisableLogGroupCreation configuration property must not be set to true. Retention policies configured in this manner are only applied to new Log Groups created directly by these libraries. By default no retention policy is applied to newly created Log Groups.

Note that any value of NewLogGroupRetentionInDays which is not one supported by CloudWatch which can be found here - and listed below - is a configuration error which will result in a non-fatal error applying the policy. The application and logging will continue however no retention policy will be applied.

null, 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1096, 1827, 2192, 2557, 2922, 3288, 3653

Supported Logging Frameworks

  1. NLog
  2. Apache log4net
  3. ASP.NET Core Logging
  4. Serilog

NLog

NLog uses targets that can be configured to receive log messages. Targets can be configured either through a config file or through code. The default config file that NLog will automatically search for is NLog.config. Here is an example config file that configures the AWS Region and the CloudWatch Logs log group.

<?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="NLog.ConfigExample" region="us-east-1"/>
  </targets>
  <rules>
    <logger name="*" minlevel="Info" writeTo="aws" />
  </rules>
</nlog>

The AWS credentials will be found using the standard AWS SDK for .NET credentials search path. In this case it will look for a profile named default, search for environment variables or search for an instance profile on an EC2 instance. To use a specific AWS credential profile use the profile attribute on the target.

Here is an example of performing the same configuration via code.

var config = new LoggingConfiguration();

var awsTarget = new AWSTarget()
{
    LogGroup = "NLog.ProgrammaticConfigurationExample",
    Region = "us-east-1"
};
config.AddTarget("aws", awsTarget);

config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, awsTarget));

LogManager.Configuration = config;

Checkout the NLog samples for examples on how you can use AWS and NLog together.

Apache log4net

Log4net configures appenders to receive log messages. Appenders can be configured either through a config file or through code. To use a config file add a file to your project. The file can be named anything but for this example call it log4net.config. Make sure that Copy to Output Directory is set to copy. Here is an example config file setting the CloudWatch Log log group and the AWS Region.

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="AWS" type="AWS.Logger.Log4net.AWSAppender,AWS.Logger.Log4net">

    <LogGroup>Log4net.ConfigExample</LogGroup>
    <Region>us-east-1</Region>
    
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-4timestamp [%thread] %-5level %logger %ndc - %message%newline" />
    </layout>
  </appender>

  <root>
    <level value="DEBUG" />
    <appender-ref ref="AWS" />
  </root>
</log4net>

The AWS credentials will be found using the standard AWS SDK for .NET credentials search path. In this case it will look for a profile named default, search for environment variables or search for an instance profile on an EC2 instance. To use a specific AWS credential profile add a Profile under the appender node.

Add the following code during the startup of the application to have log4net read the configuration file.

// log4net is configured in the log4net.config file which adds the AWS appender.
XmlConfigurator.Configure(new System.IO.FileInfo("log4net.config"));

Here is an example of performing the same configuration via code.

static void ConfigureLog4net()
{
    Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
    PatternLayout patternLayout = new PatternLayout();

    patternLayout.ConversionPattern = "%-4timestamp [%thread] %-5level %logger %ndc - %message%newline";
    patternLayout.ActivateOptions();

    AWSAppender appender = new AWSAppender();
    appender.Layout = patternLayout;

    // Set log group and region. Assume credentials will be found using the default profile or IAM credentials.
    appender.LogGroup = "Log4net.ProgrammaticConfigurationExample";
    appender.Region = "us-east-1";

    appender.ActivateOptions();
    hierarchy.Root.AddAppender(appender);

    hierarchy.Root.Level = Level.All;
    hierarchy.Configured = true;
}

Checkout the Log4net samples for examples of how you can use AWS and log4net together.

ASP.NET Core Logging

ASP.NET Core introduced a new logging framework that has providers configured to send logs to destinations. The AWS.Logger.AspNetCore NuGet package provides a log provider which adds CloudWatch Logs as a destination for the logs.

Note: Starting with version 2.0.0 of AWS.Logger.AspNetCore this library targets netstandard2.0 and the dependencies have been upgraded to the ASP.NET Core 2.1 versions. For older versions of .NET Core, which Microsoft has made end of life, use versions before 2.0.0.

The WebSample in this repository demonstrates how to configure this provider.

The configuration is setup in the appsettings.json file. In versions before 2.0.0 the AWS.Logging was used as the configuration section root. Starting with 2.0.0 the library has switched to use the standard Logging configuration section root. For backwards compatibility if the Logging section does not contain a LogGroup then the library will fallback to AWS.Logging.

"Logging": {
  "Region": "us-east-1",
  "LogGroup": "AspNetCore.WebSample",
  "IncludeLogLevel": true,
  "IncludeCategory": true,
  "IncludeNewline": true,
  "IncludeException": true,
  "IncludeEventId": false,
  "IncludeScopes": false,
  "LogLevel": {
    "Default": "Debug",
    "System": "Information",
    "Microsoft": "Information"
  }
}

In a typical ASP.NET Core application the Program.cs file contains a CreateWebHostBuilder method. To include AWS.Logger.AspNetCore add a call to ConfigureLogging and in the Action<ILoggingBuilder> passed into ConfigureLogging call AddAWSProvider. This will look up the configuration information from the IConfiguration added to the dependency injection system.

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging(logging =>
        {
            logging.AddAWSProvider();

            // When you need logging below set the minimum level. Otherwise the logging framework will default to Informational for external providers.
            logging.SetMinimumLevel(LogLevel.Debug);
        })
        .UseStartup<Startup>();

Serilog

Serilog can be configured with sinks to receive log messages either through a config file or through code. To use a config file with Serilog, follow the instructions here to install the necessary extensions and NuGet packages. In the json file, make sure AWS.Logger.SeriLog is in the Using array. Set the LogGroup and Region under the Serilog node, and add AWSSeriLog as a sink under the WriteTo node. Here is an example.

{
  "Serilog": {
    "Using": [
      "AWS.Logger.SeriLog"
    ],
    "LogGroup": "Serilog.ConfigExample",
    "Region": "us-east-1",
    "MinimumLevel": "Information",
    "WriteTo": [
      {
        "Name": "AWSSeriLog"
      }
    ]
  }
}

Add the following code to configure the logger to read from the json file.

var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();

var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();

The AWS Credentials will be found using the standard .NET credentials search path. It will search for a profile named default, environment variables, or an instance profile on an EC2 instance. In order to use a profile other than default, add a Profile under the Serilog node.

Below is an example of doing the same configuration as above via code. The AWS sink can be added to the logger by using the WriteTo method.

AWSLoggerConfig configuration = new AWSLoggerConfig("Serilog.ConfigExample");
configuration.Region = "us-east-1";

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

Checkout the Serilog samples for examples of how you can use AWS and Serilog together.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net45 is compatible.  net451 was computed.  net452 was computed.  net46 was computed.  net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (8)

Showing the top 5 NuGet packages that depend on AWS.Logger.NLog:

Package Downloads
Contensive.Processor

This package installs the library files required to create an instance of cp within an application.

Flynk.Net.Aws.Utils

Package Description

MoJ.Digital.TP.TPLibrary

Package for DynamoAPI, S3API, GuidGeneratorAPI and CloudWatchLogger

IL.Echannel.AWSCloudWatchLogging

This utility help in logging logs in aws cloud watch.

AwsnLogger

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
4.0.0-preview.1 96 10/18/2024
3.3.4 148,247 5/22/2024
3.3.3 10,997 5/15/2024
3.3.2 3,365 5/13/2024
3.3.1 20,216 4/22/2024
3.3.0 11,205 4/9/2024
3.2.1 329,385 9/14/2023
3.2.0 54,502 8/23/2023
3.1.0 1,401,179 3/21/2022
3.0.0 1,743,560 4/2/2021
2.1.0 48,661 3/25/2021
2.0.1 200,929 12/9/2020
2.0.0 413,348 10/7/2020
1.5.2 516,313 3/4/2020
1.5.1 392,970 10/17/2019
1.4.0 199,240 6/27/2019
1.3.2 65,286 5/13/2019
1.3.1 206,332 12/6/2018
1.2.0 95,592 7/24/2018
1.1.7 80,068 3/20/2018
1.1.6 9,649 2/23/2018
1.1.5 2,240 2/23/2018
1.1.4 26,742 1/4/2018
1.1.3 53,604 7/25/2017
1.1.2 3,168 6/23/2017
1.1.1 37,035 5/18/2017
1.1.0 2,385 5/8/2017
1.0.0 6,609 12/20/2016