• Stars
    star
    271
  • Rank 146,089 (Top 3 %)
  • Language
    C#
  • License
    Apache License 2.0
  • Created over 7 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

.NET Libraries for integrating Amazon CloudWatch Logs with popular .NET logging libraries

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

Why can't the Log Stream name be configured?

These libraries use CloudWatch Logs' best practice of having the log stream name be generated. The name can be customized by adding a suffix or prefix using the LogStreamNameSuffix and LogStreamNamePrefix configuration properties.

Generating the name ensures each process within an application has its own log stream to write to. When writing to log stream a marker is maintained to append more messages to the stream. When more then one process writes to the same stream the marker maintained within the process goes out of sync. This generates errors and retries to post the log message causing performance issues.

To view logs across all log streams it is recommended to use the Logs Insight feature for Cloud Watch Logs.

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.

More Repositories

1

aws-cli

Universal Command Line Interface for Amazon Web Services
Python
14,304
star
2

aws-cdk

The AWS Cloud Development Kit is a framework for defining cloud infrastructure in code
JavaScript
10,440
star
3

chalice

Python Serverless Microframework for AWS
Python
10,191
star
4

amazon-sagemaker-examples

Example ๐Ÿ““ Jupyter notebooks that demonstrate how to build, train, and deploy machine learning models using ๐Ÿง  Amazon SageMaker.
Jupyter Notebook
9,297
star
5

serverless-application-model

The AWS Serverless Application Model (AWS SAM) transform is a AWS CloudFormation macro that transforms SAM templates into CloudFormation templates.
Python
9,235
star
6

aws-sdk-js

AWS SDK for JavaScript in the browser and Node.js
JavaScript
7,476
star
7

aws-sam-cli

CLI tool to build, test, debug, and deploy Serverless applications using AWS SAM
Python
6,443
star
8

aws-sdk-php

Official repository of the AWS SDK for PHP (@awsforphp)
PHP
5,886
star
9

containers-roadmap

This is the public roadmap for AWS container services (ECS, ECR, Fargate, and EKS).
Shell
5,119
star
10

karpenter

Karpenter is a Kubernetes Node Autoscaler built for flexibility, performance, and simplicity.
Go
4,615
star
11

s2n-tls

An implementation of the TLS/SSL protocols
C
4,447
star
12

aws-sdk-java

The official AWS SDK for Java 1.x. The AWS SDK for Java 2.x is available here: https://github.com/aws/aws-sdk-java-v2/
4,064
star
13

aws-sdk-pandas

pandas on AWS - Easy integration with Athena, Glue, Redshift, Timestream, Neptune, OpenSearch, QuickSight, Chime, CloudWatchLogs, DynamoDB, EMR, SecretManager, PostgreSQL, MySQL, SQLServer and S3 (Parquet, CSV, JSON and EXCEL).
Python
3,537
star
14

aws-lambda-go

Libraries, samples and tools to help Go developers develop AWS Lambda functions.
Go
3,498
star
15

aws-sdk-ruby

The official AWS SDK for Ruby.
Ruby
3,462
star
16

copilot-cli

The AWS Copilot CLI is a tool for developers to build, release and operate production ready containerized applications on AWS App Runner or Amazon ECS on AWS Fargate.
Go
3,274
star
17

amazon-freertos

DEPRECATED - See README.md
C
2,535
star
18

aws-sdk-js-v3

Modularized AWS SDK for JavaScript.
TypeScript
2,476
star
19

jsii

jsii allows code in any language to naturally interact with JavaScript classes. It is the technology that enables the AWS Cloud Development Kit to deliver polyglot libraries from a single codebase!
TypeScript
2,371
star
20

aws-sdk-go-v2

AWS SDK for the Go programming language.
Go
2,298
star
21

amazon-vpc-cni-k8s

Networking plugin repository for pod networking in Kubernetes using Elastic Network Interfaces on AWS
Go
2,071
star
22

sagemaker-python-sdk

A library for training and deploying machine learning models on Amazon SageMaker
Python
2,038
star
23

amazon-ecs-agent

Amazon Elastic Container Service Agent
Go
2,005
star
24

lumberyard

Amazon Lumberyard is a free AAA game engine deeply integrated with AWS and Twitch โ€“ with full source.
C++
1,965
star
25

aws-sdk-net

The official AWS SDK for .NET. For more information on the AWS SDK for .NET, see our web site:
1,945
star
26

eks-anywhere

Run Amazon EKS on your own infrastructure ๐Ÿš€
Go
1,899
star
27

aws-eks-best-practices

A best practices guide for day 2 operations, including operational excellence, security, reliability, performance efficiency, and cost optimization.
Python
1,853
star
28

aws-sdk-java-v2

The official AWS SDK for Java - Version 2
Java
1,822
star
29

aws-sdk-cpp

AWS SDK for C++
1,779
star
30

amazon-ecs-cli

The Amazon ECS CLI enables users to run their applications on ECS/Fargate using the Docker Compose file format, quickly provision resources, push/pull images in ECR, and monitor running applications on ECS/Fargate.
Go
1,725
star
31

aws-sdk-php-laravel

A Laravel 5+ (and 4) service provider for the AWS SDK for PHP
PHP
1,589
star
32

aws-node-termination-handler

Gracefully handle EC2 instance shutdown within Kubernetes
Go
1,443
star
33

serverless-java-container

A Java wrapper to run Spring, Spring Boot, Jersey, and other apps inside AWS Lambda.
Java
1,439
star
34

aws-lambda-dotnet

Libraries, samples and tools to help .NET Core developers develop AWS Lambda functions.
C#
1,430
star
35

aws-fpga

Official repository of the AWS EC2 FPGA Hardware and Software Development Kit
VHDL
1,380
star
36

eks-distro

Amazon EKS Distro (EKS-D) is a Kubernetes distribution based on and used by Amazon Elastic Kubernetes Service (EKS) to create reliable and secure Kubernetes clusters.
Shell
1,263
star
37

aws-toolkit-vscode

CodeWhisperer, CodeCatalyst, Local Lambda debug, SAM/CFN syntax, ECS Terminal, AWS resources
TypeScript
1,150
star
38

eks-charts

Amazon EKS Helm chart repository
Mustache
1,142
star
39

s2n-quic

An implementation of the IETF QUIC protocol
Rust
1,066
star
40

opsworks-cookbooks

Chef Cookbooks for the AWS OpsWorks Service
Ruby
1,058
star
41

aws-codebuild-docker-images

Official AWS CodeBuild repository for managed Docker images http://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref.html
Dockerfile
1,032
star
42

amazon-ssm-agent

An agent to enable remote management of your EC2 instances, on-premises servers, or virtual machines (VMs).
Go
975
star
43

aws-iot-device-sdk-js

SDK for connecting to AWS IoT from a device using JavaScript/Node.js
JavaScript
957
star
44

aws-iot-device-sdk-embedded-C

SDK for connecting to AWS IoT from a device using embedded C.
C
926
star
45

aws-health-tools

The samples provided in AWS Health Tools can help users to build automation and customized alerting in response to AWS Health events.
Python
887
star
46

aws-app-mesh-examples

AWS App Mesh is a service mesh that you can use with your microservices to manage service to service communication.
Shell
844
star
47

deep-learning-containers

AWS Deep Learning Containers (DLCs) are a set of Docker images for training and serving models in TensorFlow, TensorFlow 2, PyTorch, and MXNet.
Python
800
star
48

aws-graviton-getting-started

Helping developers to use AWS Graviton2 and Graviton3 processors which power the 6th and 7th generation of Amazon EC2 instances (C6g[d], M6g[d], R6g[d], T4g, X2gd, C6gn, I4g, Im4gn, Is4gen, G5g, C7g[d][n], M7g[d], R7g[d]).
Python
788
star
49

aws-parallelcluster

AWS ParallelCluster is an AWS supported Open Source cluster management tool to deploy and manage HPC clusters in the AWS cloud.
Python
782
star
50

aws-lambda-runtime-interface-emulator

Go
771
star
51

aws-toolkit-jetbrains

AWS Toolkit for JetBrains - a plugin for interacting with AWS from JetBrains IDEs
Kotlin
723
star
52

aws-iot-device-sdk-python

SDK for connecting to AWS IoT from a device using Python.
Python
670
star
53

graph-notebook

Library extending Jupyter notebooks to integrate with Apache TinkerPop, openCypher, and RDF SPARQL.
Jupyter Notebook
663
star
54

amazon-chime-sdk-js

A JavaScript client library for integrating multi-party communications powered by the Amazon Chime service.
TypeScript
655
star
55

amazon-ec2-instance-selector

A CLI tool and go library which recommends instance types based on resource criteria like vcpus and memory
Go
642
star
56

studio-lab-examples

Example notebooks for working with SageMaker Studio Lab. Sign up for an account at the link below!
Jupyter Notebook
566
star
57

aws-sdk-rails

Official repository for the aws-sdk-rails gem, which integrates the AWS SDK for Ruby with Ruby on Rails.
Ruby
554
star
58

aws-mwaa-local-runner

This repository provides a command line interface (CLI) utility that replicates an Amazon Managed Workflows for Apache Airflow (MWAA) environment locally.
Shell
553
star
59

amazon-eks-pod-identity-webhook

Amazon EKS Pod Identity Webhook
Go
534
star
60

event-ruler

Event Ruler is a Java library that allows matching many thousands of Events per second to any number of expressive and sophisticated rules.
Java
516
star
61

aws-lambda-base-images

506
star
62

aws-lambda-java-libs

Official mirror for interface definitions and helper classes for Java code running on the AWS Lambda platform.
C++
502
star
63

aws-appsync-community

The AWS AppSync community
HTML
495
star
64

dotnet

GitHub home for .NET development on AWS
487
star
65

aws-cdk-rfcs

RFCs for the AWS CDK
JavaScript
476
star
66

sagemaker-training-toolkit

Train machine learning models within a ๐Ÿณ Docker container using ๐Ÿง  Amazon SageMaker.
Python
468
star
67

aws-elastic-beanstalk-cli-setup

Simplified EB CLI installation mechanism.
Python
453
star
68

aws-sam-cli-app-templates

Python
435
star
69

amazon-cloudwatch-agent

CloudWatch Agent enables you to collect and export host-level metrics and logs on instances running Linux or Windows server.
Go
403
star
70

secrets-store-csi-driver-provider-aws

The AWS provider for the Secrets Store CSI Driver allows you to fetch secrets from AWS Secrets Manager and AWS Systems Manager Parameter Store, and mount them into Kubernetes pods.
Go
393
star
71

amazon-braket-examples

Example notebooks that show how to apply quantum computing in Amazon Braket.
Python
376
star
72

aws-for-fluent-bit

The source of the amazon/aws-for-fluent-bit container image
Shell
375
star
73

aws-extensions-for-dotnet-cli

Extensions to the dotnet CLI to simplify the process of building and publishing .NET Core applications to AWS services
C#
346
star
74

aws-sdk-php-symfony

PHP
346
star
75

aws-app-mesh-roadmap

AWS App Mesh is a service mesh that you can use with your microservices to manage service to service communication
344
star
76

aws-iot-device-sdk-python-v2

Next generation AWS IoT Client SDK for Python using the AWS Common Runtime
Python
335
star
77

constructs

Define composable configuration models through code
TypeScript
332
star
78

aws-lambda-builders

Python library to compile, build & package AWS Lambda functions for several runtimes & framework
Python
325
star
79

aws-codedeploy-agent

Host Agent for AWS CodeDeploy
Ruby
316
star
80

aws-sdk-ruby-record

Official repository for the aws-record gem, an abstraction for Amazon DynamoDB.
Ruby
313
star
81

aws-ops-wheel

The AWS Ops Wheel is a randomizer that biases for options that havenโ€™t come up recently; you can also outright cheat and specify the next result to be generated.
JavaScript
308
star
82

aws-xray-sdk-python

AWS X-Ray SDK for the Python programming language
Python
304
star
83

sagemaker-inference-toolkit

Serve machine learning models within a ๐Ÿณ Docker container using ๐Ÿง  Amazon SageMaker.
Python
303
star
84

aws-pdk

The AWS PDK provides building blocks for common patterns together with development tools to manage and build your projects.
TypeScript
288
star
85

amazon-ivs-react-native-player

A React Native wrapper for the Amazon IVS iOS and Android player SDKs.
TypeScript
283
star
86

sagemaker-spark

A Spark library for Amazon SageMaker.
Scala
282
star
87

pg_tle

Framework for building trusted language extensions for PostgreSQL
C
282
star
88

apprunner-roadmap

This is the public roadmap for AWS App Runner.
280
star
89

graph-explorer

React-based web application that enables users to visualize both property graph and RDF data and explore connections between data without having to write graph queries.
TypeScript
278
star
90

aws-xray-sdk-go

AWS X-Ray SDK for the Go programming language.
Go
274
star
91

aws-toolkit-eclipse

(End of life: May 31, 2023) AWS Toolkit for Eclipse
Java
273
star
92

elastic-beanstalk-roadmap

AWS Elastic Beanstalk roadmap
272
star
93

sagemaker-tensorflow-training-toolkit

Toolkit for running TensorFlow training scripts on SageMaker. Dockerfiles used for building SageMaker TensorFlow Containers are at https://github.com/aws/deep-learning-containers.
Python
267
star
94

elastic-load-balancing-tools

AWS Elastic Load Balancing Tools
Java
262
star
95

aws-step-functions-data-science-sdk-python

Step Functions Data Science SDK for building machine learning (ML) workflows and pipelines on AWS
Python
261
star
96

efs-utils

Utilities for Amazon Elastic File System (EFS)
Python
257
star
97

amazon-braket-sdk-python

A Python SDK for interacting with quantum devices on Amazon Braket
Python
254
star
98

aws-xray-sdk-node

The official AWS X-Ray SDK for Node.js.
JavaScript
248
star
99

Trusted-Advisor-Tools

The sample functions provided help to automate AWS Trusted Advisor best practices using Amazon Cloudwatch events and AWS Lambda.
Python
242
star
100

amazon-chime-sdk-component-library-react

Amazon Chime React Component Library with integrations with the Amazon Chime SDK.
TypeScript
240
star