Coder Social home page Coder Social logo

aws-logging-dotnet's Introduction

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.

aws-logging-dotnet's People

Contributors

96malhar avatar aaronamm avatar alexbathome avatar ashishdhingra avatar ashovlin avatar augustoproiete avatar bartpio avatar costleya avatar dependabot[bot] avatar elanhasson avatar forensicmike avatar henrymaosydney avatar herdo avatar hyandell avatar kellertk avatar michaeldimoudis avatar monty241 avatar ngl321 avatar normj avatar peterrsongg avatar philasmar avatar ppittle avatar ryannewington avatar sattpat avatar snakefoot avatar somayab avatar srutig avatar vellozzi avatar will-dbg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aws-logging-dotnet's Issues

NLog successfully creates the logging group, but not any log events

Here is where I configure the logger with code:

public ILogger GetLogger() {
 if (logger != null) {
  return logger;
 }
 var config = new LoggingConfiguration();

 var consoleTarget = new ColoredConsoleTarget();
 config.AddTarget("console", consoleTarget);

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

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

 LogManager.Configuration = config;
 return LogManager.GetCurrentClassLogger();
}

This is how I call it:

_logger.Debug(response.Content.ReadAsStringAsync().Result);
 _logger.Debug("hey!");

The AWS profile has the following access:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents",
        "logs:DescribeLogGroups"
      ],
      "Resource": [
        "arn:aws:logs:*:*:*"
      ]
    }
  ]
}

I also tried it with a profile with full access, and it still didn't work. What am I missing here? Is there a way I can debug this?

Log groups stop collecting entries after some variable amount of time

We're seeing this issue with dotnet core 2 applications using the latest AWS.Logger.AspNetCore package. The applications and logging functions as expected after a deployment but after some amount of time (have seen ~1 day up to ~1 week) there are no new entries in the log group.

The setup is vanilla, the log provider is added in Configure if the environment is production (in Startup.cs)
loggerFactory.AddAWSProvider(Configuration.GetAWSLoggingConfigSection());

And the relevant config in appsettings.json is

"AWS.Logging": {
    "LogGroup": "MyGroupName",
    "LogLevel": {
      "MyNamespace" : "Information",
      "System": "Warning",
      "Microsoft": "Information",
      "Default": "Information"
    }
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "MyNamespace" : "Information",
      "System": "Warning",
      "Microsoft": "Information",
      "Default": "Information"
    }
  }

The applications continue to function as expected, processing requests, which indicates that calls are continuing to be made to the ILogger instance (which is DI'd into all controllers and other objects that need logging). But no logs are collected in CloudWatch after some amount of time has passed.

The only workaround I've found is to redeploy the application. This causes the log groups in CloudWatch to once again collect entries.

I've seen this with applications running on EC2 c4.large instances or t2.small instances and in both private and public VPC subnets. The instances are not under much load when the logging stops working, minimal CPU use and lots of available memory.

Is this a known problem w/ either the package or CloudWatch? How would we go about debugging this further?

Log message more than 256K blocks Logger and causes elevated CPU load

We ran into several cases when accidentally too large individual log message, more than 256K individual log message limit of the CloudWatch, has blocked Logger from sending subsequent messages and also caused increased CPU load, because logger was trying to resend it indefinitely. Here is the stack trace from the individual failure to send the message, which was repeated approx every 2 seconds:

-------------------------------
Log Entry : 
3/13/2018 11:43:47 AM
  :
  :Amazon.CloudWatchLogs.Model.InvalidParameterException: Log event too large: 304112 bytes exceeds limit of 262144 ---> Amazon.Runtime.Internal.HttpErrorResponseException: The remote server returned an error: (400) Bad Request. ---> System.Net.WebException: The remote server returned an error: (400) Bad Request.
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.HttpRequest.<GetResponseAsync>d__16.MoveNext()
   --- End of inner exception stack trace ---
   at Amazon.Runtime.Internal.HttpRequest.<GetResponseAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.HttpHandler`1.<InvokeAsync>d__9`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.Unmarshaller.<InvokeAsync>d__3`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.ErrorHandler.<InvokeAsync>d__5`1.MoveNext()
   --- End of inner exception stack trace ---
   at Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleException(IExecutionContext executionContext, HttpErrorResponseException exception)
   at Amazon.Runtime.Internal.ErrorHandler.ProcessException(IExecutionContext executionContext, Exception exception)
   at Amazon.Runtime.Internal.ErrorHandler.<InvokeAsync>d__5`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.CallbackHandler.<InvokeAsync>d__9`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.CredentialsRetriever.<InvokeAsync>d__7`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.RetryHandler.<InvokeAsync>d__10`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Amazon.Runtime.Internal.RetryHandler.<InvokeAsync>d__10`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.CallbackHandler.<InvokeAsync>d__9`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.CallbackHandler.<InvokeAsync>d__9`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.ErrorCallbackHandler.<InvokeAsync>d__5`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.MetricsHandler.<InvokeAsync>d__1`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at AWS.Logger.Core.AWSLoggerCore.<SendMessages>d__23.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at AWS.Logger.Core.AWSLoggerCore.<Monitor>d__22.MoveNext()
-------------------------------

I suggest to implement safer behavior for the AWS.Logger.Core.AWSLoggerCore.Monitor call and truncate each log message up to the limit, rather than run into described difficulties. Currently it only checks if new log message causes the batch to break the size limit when added to it, but does not handle the case when individual message is too big.

Separately, retry logic for failed attempts to send log message batch would work nicer if it would use exponential backoff and eventually stop resending and posting message on the failure to send original message to the log. Current behavior of handling non-recoverable error does not lead to any success and just hogs the CPU. If retry logic cannot do anything useful, it should at least stop trying and attempt to send failure message to the log once, and then try new batch again (with the hope that failure was due to the batch content and new one can go), applying the same retry logic to it.

Value null at 'logEvents' failed to satisfy constraint: Member must not be null

Occasionally my application encounters an exception which gets logged in the LibraryLog, attached here is an example. When this happens, logs stop getting ingested for some time, usually hours, until the application seems to recover and continue delivering logs where it left off. I assume the correlation as I see logs appear in Cloudwatch Logs with a much later ingestion timestamp relative to the log entry, with the gap beginning at the time I see the exceptions in the LibraryLog.

During these periods it seems the internal buffer is all the while filling, as I will also see The AWS Logger in-memory buffer has reached maximum capacity entries in the application's log stream. When this happens it appears the application drops log entries.

It's possible the application is doing something silly and/or preventable, but I don't expect it should be possible for it to put the library in this state. If I can determine that the app is doing something preventable I will post my findings here.

Thank you!

LibraryLog.txt

AWSAppender adds empty CW entry after app pool recycle

So this seems to be related to the fact that log4net locks and creates an empty log file on startup. When this occurs with the AWSAppender, it creates a blank entry in CloudWatch with no events. Is there a way to disable this behavior?

Here's some images:

image

And when you browse to that log stream:

image

This is a workaround for the RollingFileAppender, but i'm not sure if it applies to the Cloudwatch functionality here:

https://stackoverflow.com/questions/2533403/how-to-disable-creation-of-empty-log-file-on-app-start

Logger does not seem to be reliable long-term

I'm attempting to use the AWS Cloudwatch .Net Core logger in a process that handles large amounts of data in a multi-threaded fashion. We're hosting this process in ECS, so Cloudwatch seemed natural. I've tried a few things, such as registering my LoggerFactory as a transient service:

serviceCollection.AddTransient<ILoggerFactory>((s) => new LoggerFactory()
            .WithFilter(new FilterLoggerSettings
                {
                    { "Microsoft", LogLevel.Warning },
                    { "System", LogLevel.Warning }
                })
                .AddAWSProvider(
                new AWS.Logger.AWSLoggerConfig
                {
                    Region = "xxxxxx",
                    LogGroup = "xxxxxxxx",
                    MaxQueuedMessages = Int32.MaxValue,
                    BatchPushInterval = new TimeSpan(0, 0, 0, 1)
                },
                LogLevel.Debug
                )
                .AddConsole(LogLevel.Error)
            );

And also getting the logger as a function in hopes of creating it anew:

serviceCollection.AddSingleton<Func<ILogger>>((IServiceProvider provider) => { return () => provider.GetRequiredService<ILogger<App>>(); });

But it seems that no matter what, the logger eventually dies silently and won't come back. The application continues to run, but no more messages appear in the log.

This is an example of the messages I see in aws-logger-errors.txt:

Log Entry :
2/12/2018 10:41:49 PM
:
:Amazon.Runtime.AmazonUnmarshallingException: Error unmarshalling response back from AWS. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at Amazon.Runtime.Internal.Transform.JsonErrorResponseUnmarshaller.Unmarshall(JsonUnmarshallerContext context) in E:\JenkinsWorkspaces\v3-stage-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Internal\Transform\JsonErrorResponseUnmarshaller.cs:line 103
at Amazon.CloudWatchLogs.Model.Internal.MarshallTransformations.PutLogEventsResponseUnmarshaller.UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
at Amazon.Runtime.Internal.Transform.JsonResponseUnmarshaller.UnmarshallException(UnmarshallerContext input, Exception innerException, HttpStatusCode statusCode) in E:\JenkinsWorkspaces\v3-stage-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Internal\Transform\ResponseUnmarshallers.cs:line 198
at Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleException(IExecutionContext executionContext, HttpErrorResponseException exception) in E:\JenkinsWorkspaces\v3-stage-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\ErrorHandler\HttpErrorResponseExceptionHandler.cs:line 78
--- End of inner exception stack trace ---

AWS.Logger.AspNetCore: Send exception messages to CloudWatch

I am trying to send Exception messages to Cloudwatch, but seems that it doesn't work that way.

Is there a way I can send the Exception Message or Exception Stacktrace to Cloudwatch ?

Using the code below I only gets "Error message".

logger.LogError(0, new ApplicationException("Exception message."), "Error message");

Thanks in advance.

NLog not sending logs to CloudWatch

NLog not sending logs to CloudWatch

Target frameword
<TargetFramework>netcoreapp1.0</TargetFramework>

Packages

<PackageReference Include="AWS.Logger.Core" Version="1.1.4" />
<PackageReference Include="AWS.Logger.NLog" Version="1.1.4" />
<PackageReference Include="NLog" Version="5.0.0-beta07" />
<PackageReference Include="Amazon.Lambda.Core" Version="1.0.0" />
<PackageReference Include="Amazon.Lambda.Logging.AspNetCore" Version="1.1.0" />
<PackageReference Include="Amazon.Lambda.Serialization.Json" Version="1.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="1.0.1" />
...

NLog.config

<?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"
      throwExceptions="true"
      internalLogToConsole="true"
      internalLogLevel="Trace">
  <extensions> <add assembly="NLog.AWS.Logger" /> </extensions>
  <targets>
    
    <target name="awsout" type="AWSTarget" logGroup="critical-errors" region="eu-central-1"> 
      <layout xsi:type="JsonLayout" includeAllProperties="true"> 
        <attribute name="time" layout="${longdate}" /> 
        <attribute name="level" layout="${level:upperCase=true}"/> 
        <attribute name="message" layout="${message}" encode="false" /> 
        <attribute name="stack-trace" layout="${stacktrace:format=Raw:topFrames=5}"/> 
      </layout> 
    </target>
    </targets>
  <rules>
    <logger name="CriticalErrors" minlevel="Info" writeTo="awsout" />
  </rules>
</nlog>

Code

Logger Logger = LogManager.GetLogger("CriticalErrors");
Logger.Error(() => JsonConvert.SerializeObject(new Dictionary<string, object>
            {
                {"UNKNOWN-ERROR", internalError.GetLogCode()},
                {"ERROR-TYPE", "UNKNOWN"},
                {"PAYLOAD", stackTrace}
            }));

What am I doing wrong?

Cloud watch with log4net API

Hi,

I am trying to integrate log4net API to push all application logs directly to Cloud watch. This is working fine. But message in json format is truncated. I am trying to log API request and response content. My API is using following JSON format for request/response.

{
"Name": "SyncAPI",
"Message": {
"LastSyncNo": 100
},
"Status": {
"Success": false,
"Code": 422
}
}

Following layout pattern is used in log4net configuration. Could you please help me to log data in above mentioned JSON format using log4net?

<layout type="AWSAppender.Core.Layout.PatternLayout, AWSAppender.Core"> <conversionPattern value="%date [%thread] %-5level %message" /> </layout>

Regards,
Princy

Can I create a stream per log level?

When AWS decides to create a new log stream?
When logging, inside my logGroup I want only few streams, each for a log level, is this possible? does AWS provide such ability?
Note: No automatic log streams should be created

run ConfigExample throw exception.

:System.OperationCanceledException: The request was aborted: The request was canceled. ---> System.Net.WebException: The request was aborted: The request was canceled.
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Amazon.Runtime.Internal.HttpRequest.d__16.MoveNext()
--- End of inner exception stack trace ---
at Amazon.Runtime.Internal.HttpRequest.d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Amazon.Runtime.Internal.HttpHandler1.<InvokeAsync>d__91.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Amazon.Runtime.Internal.Unmarshaller.d__31.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Amazon.Runtime.Internal.ErrorHandler.<InvokeAsync>d__51.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Amazon.Runtime.Internal.CallbackHandler.d__91.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Amazon.Runtime.Internal.CredentialsRetriever.<InvokeAsync>d__71.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Amazon.Runtime.Internal.RetryHandler.d__101.MoveNext() --- End of stack trace from previous location where exception was thrown --- at Amazon.Runtime.Internal.RetryHandler.<InvokeAsync>d__101.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Amazon.Runtime.Internal.CallbackHandler.d__91.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Amazon.Runtime.Internal.CallbackHandler.<InvokeAsync>d__91.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Amazon.Runtime.Internal.ErrorCallbackHandler.d__51.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Amazon.Runtime.Internal.MetricsHandler.<InvokeAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at AWS.Logger.Core.AWSLoggerCore.d__22.MoveNext()

IAM policy

Hey there,

I have a very hard time figuring out what IAM policy I should use for this to work. Apparently event the CloudWatchLogsFullAccess doesn't seem to work. What other access rights (apart from logs functions) are needed for this to work properly ?

Thanks a lot for your help.

NLog ReconfigureExistingLoggers does not pick up change to AWSTarget.LogGroup

I have a problem with AWS.Logger.NLog 1.1.7 on .Net Core 2.1 and programmatically changing CloudWatch Log Group. As far as I understand, setting property AWSTarget.LogGroup and then running NLog.LogManager.ReconfigExistingLoggers should redirect logs to new log group. However what I am seeing is logs still going to the original log group.

The following code reproduces the problem:

NLog.config:

<?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"
      throwExceptions="true">
  <extensions>
    <add assembly="NLog.AWS.Logger" />
  </extensions>
  <targets>
    <target
      name="aws"
      xsi:type="AWSTarget"
      logGroup="AwsNlogTest"
      region="eu-west-1"
      layout="${message}"/>
  </targets>
  <rules>
    <logger name="*" minlevel="Debug" writeTo="aws" />
  </rules>
</nlog>

ReconfigTest.cs:

using NLog;
using NLog.AWS.Logger;

namespace AwsNlogReconfig
{
    class ReconfigTest
    {
        static void Main(string[] args)
        {
            Logger logger = LogManager.GetCurrentClassLogger();
            logger.Info("Message to original log group"); // Works as expected

            var awsTarget = LogManager.Configuration.FindTargetByName("aws") as AWSTarget;
            awsTarget.LogGroup += "-suffix";
            LogManager.ReconfigExistingLoggers();

            logger.Info("Message to new log group"); // Still sends to original log group
        }
    }
}

Evaluate NLog parameters in AwsTarget Class

Hi,

I found out that NLog parameters are NOT evaluated when they are passed to the AWSTarget.
Any variable, or renderers used within these parameters will not get evaluated.

For instance:

        [RequiredParameter]
        public string LogGroup
        {
            get { return _config.LogGroup; }
            set { _config.LogGroup = value; }
        }

Does not evaluate code like: ${when:when='${environment:ASPNETCORE_ENVIRONMENT}'=='Production':inner=prd:else=uat}

To make it work, I had to change the AwsTarget class and call SimpleLayout.Evaluate when assigning value to AWSLoggerConfig.

        [RequiredParameter]
        public string LogGroup
        {
            get => _config.LogGroup;
            set => _config.LogGroup = SimpleLayout.Evaluate(value);
        }

I'm not sure it's a good practice, but it solved my "issue"

ASP.NET Core Log event ID support

Is there some way to pass Log event ID to formatter and then filter logs by that same ID?

Wright now our formatter looks like this:
formatter: (logLevel, message, exception) => $"[{DateTime.UtcNow}] {logLevel}: {message} \n {exception}")); and I can't find a way to pass log event ID except inside a message.

I think this feature would be very useful and it's kind of a "core" for every logging library.

System.OperationCanceledException: The request was aborted

I've provided role to EC2 but i'm facing aws-logger-error.txt

:System.OperationCanceledException: The request was aborted: The request was canceled. ---> System.Net.WebException: The request was aborted: The request was canceled.
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Amazon.Runtime.Internal.HttpRequest.d__16.MoveNext()
--- End of inner exception stack trace ---
at Amazon.Runtime.Internal.HttpRequest.d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---

Quick tool becomes slow due to AWSLoggerCore.Close() call in finalizer

We were recently investigating some performance issues with our in-house tooling, specifically a strange pause between completing all processing and a few seconds where nothing appears to be happening before our tool releases control back to the command line.

After some troubleshooting we ran dotTrace, to try to see what was happening. A call was logged by the Finalizer for about 1 and a half seconds to AWSLoggerCore.Close().

We tried to call this explicitly but have not found anyway to expose the AWSLoggerCore class instance so that we can call the function ourselves. Is there some way to reach it? If not, shouldn't there be a way so that we can manage it's closing when we desire it and provide messaging to the user like Closing AWSLoggerCore....

Any help would be greatly appreciated. I can't do a minimal reproducible case right now, but will try to get around to it at some point tomorrow if you're having trouble reproducing this issue.

Error AWSTarget Target[(unnamed)]: Error initializing target Exception:

Error AWSTarget Target[(unnamed)]: Error initializing target Exception: System.TypeLoadException:
Could not resolve type with token 01000043
(from typeref, class/assembly Amazon.Runtime.CredentialManagement.CredentialProfileStoreChain, AWSSDK.Core, Version=3.3.0.0, Culture=neutral, PublicKeyToken=885c28607f98e604)
at AWS.Logger.Core.AWSLoggerCore..ctor (AWS.Logger.AWSLoggerConfig config, System.String logType) [0x0002a] in D:\Jenkins\jobs\aws-logging-dotnet\workspace\src\AWS.Logger.Core\Core\AWSLoggerCore.cs:43
at NLog.AWS.Logger.AWSTarget.InitializeTarget () [0x00092] in D:\Jenkins\jobs\aws-logging-dotnet\workspace\src\NLog.AWS.Logger\AWSTarget.cs:178
at NLog.Targets.Target.Initialize (NLog.Config.LoggingConfiguration configuration) [0x00026] in :0

Amazon.Runtime.AmazonUnmarshallingException: Error unmarshalling response back from AWS.

From time to time I am facing the following exception in aws-logger-error.txt, after which the logs going through the appender affected by this exception stop showing up in CloudWatch:

 :Amazon.Runtime.AmazonUnmarshallingException: Error unmarshalling response back from AWS.  ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at Amazon.Runtime.Internal.Transform.JsonErrorResponseUnmarshaller.Unmarshall(JsonUnmarshallerContext context)
   at Amazon.CloudWatchLogs.Model.Internal.MarshallTransformations.PutLogEventsResponseUnmarshaller.UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
   at Amazon.Runtime.Internal.Transform.JsonResponseUnmarshaller.UnmarshallException(UnmarshallerContext input, Exception innerException, HttpStatusCode statusCode)
   at Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleException(IExecutionContext executionContext, HttpErrorResponseException exception)
   --- End of inner exception stack trace ---
   at Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleException(IExecutionContext executionContext, HttpErrorResponseException exception)
   at Amazon.Runtime.Internal.ErrorHandler.ProcessException(IExecutionContext executionContext, Exception exception)
   at Amazon.Runtime.Internal.ErrorHandler.<InvokeAsync>d__5`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.CallbackHandler.<InvokeAsync>d__9`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.CredentialsRetriever.<InvokeAsync>d__7`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.RetryHandler.<InvokeAsync>d__10`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Amazon.Runtime.Internal.RetryHandler.<InvokeAsync>d__10`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.CallbackHandler.<InvokeAsync>d__9`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.CallbackHandler.<InvokeAsync>d__9`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.ErrorCallbackHandler.<InvokeAsync>d__5`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.MetricsHandler.<InvokeAsync>d__1`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at AWS.Logger.Core.AWSLoggerCore.<SendMessages>d__23.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at AWS.Logger.Core.AWSLoggerCore.<Monitor>d__22.MoveNext()
-------------------------------

I believe exception might be related to some intermittent issue with CloudWatch API.

The problem is that this exception is breaking main cycle in the AWSLoggerCore.Monitor method, so no further log messages are sent to the API. The try-catch block in the method is not rethrowing general exceptions, but it is still outside the main cycle so exceptions break it.

I think Monitor could be made more resilient to such errors by moving/adding try-catch block within the main cycle.

The security token included in the request is invalid

I've been unable to get the project working in my Core 1.0 environment. Below is the error I receive when calling the LogInformation method.

:Amazon.CloudWatchLogs.AmazonCloudWatchLogsException: The security token included in the request is invalid. ---> Amazon.Runtime.Internal.HttpErrorResponseException: Exception of type 'Amazon.Runtime.Internal.HttpErrorResponseException' was thrown.
at Amazon.Runtime.HttpWebRequestMessage.d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Amazon.Runtime.Internal.HttpHandler1.<InvokeAsync>d__91.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Amazon.Runtime.Internal.Unmarshaller.d__31.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Amazon.Runtime.Internal.ErrorHandler.<InvokeAsync>d__51.MoveNext()
--- End of inner exception stack trace ---
at Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleException(IExecutionContext executionContext, HttpErrorResponseException exception)
at Amazon.Runtime.Internal.ErrorHandler.ProcessException(IExecutionContext executionContext, Exception exception)
at Amazon.Runtime.Internal.ErrorHandler.d__51.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Amazon.Runtime.Internal.CallbackHandler.<InvokeAsync>d__91.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Amazon.Runtime.Internal.CredentialsRetriever.d__71.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Amazon.Runtime.Internal.RetryHandler.<InvokeAsync>d__101.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Amazon.Runtime.Internal.RetryHandler.d__101.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Amazon.Runtime.Internal.CallbackHandler.<InvokeAsync>d__91.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Amazon.Runtime.Internal.CallbackHandler.d__91.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Amazon.Runtime.Internal.ErrorCallbackHandler.<InvokeAsync>d__51.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Amazon.Runtime.Internal.MetricsHandler.d__1`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at AWS.Logger.Core.AWSLoggerCore.d__22.MoveNext() in D:\Jenkins\jobs\aws-logging-dotnet\workspace\src\AWS.Logger.Core\Core\AWSLoggerCore.cs:line 264

Method 'get_ServiceMetadata' in type 'Amazon.CloudWatchLogs.AmazonCloudWatchLogsClient' from assembly 'AWSSDK.CloudWatchLogs, Version=3.3.0.0, Culture=neutral, PublicKeyToken=885c28607f98e604' does not have an implementation.

Trying to use AWS Target for NLog or log4net, both fail with the same error.

NLog:

var config = new LoggingConfiguration();
var awsTarget = new AWSTarget()
{
	LogGroup = Environment.GetEnvironmentVariable("AWS_LAMBDA_LOG_GROUP_NAME"),
	Region = Environment.GetEnvironmentVariable("AWS_DEFAULT_REGION")
};

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

LogManager.Configuration = config;
LogManager.ThrowConfigExceptions = true;
LogManager.ThrowExceptions = true;
One or more errors occurred. (Exception occurred in NLog): AggregateException
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at lambda_method(Closure , Stream , Stream , LambdaContextInternal )

at NLog.LoggerImpl.<>c__DisplayClass1_0.<Write>b__1(Exception ex)
at NLog.Targets.Target.WriteAsyncLogEvent(AsyncLogEventInfo logEvent)
at NLog.LoggerImpl.WriteToTargetWithFilterChain(Target target, FilterResult result, LogEventInfo logEvent, AsyncContinuation onException)
at NLog.LoggerImpl.Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
at ...
at ...
Target AWSTarget Target[(unnamed)] failed to initialize.: NLogRuntimeException
Method 'get_ServiceMetadata' in type 'Amazon.CloudWatchLogs.AmazonCloudWatchLogsClient' from assembly 'AWSSDK.CloudWatchLogs, Version=3.3.0.0, Culture=neutral, PublicKeyToken=885c28607f98e604' does not have an implementation.: TypeLoadException
at AWS.Logger.Core.AWSLoggerCore..ctor(AWSLoggerConfig config, String logType)
at NLog.AWS.Logger.AWSTarget.InitializeTarget()
at NLog.Targets.Target.Initialize(LoggingConfiguration configuration)

log4net:

Hierarchy hierarchy = (Hierarchy)LogManager.CreateRepository(Repository);
PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = "%-4timestamp [%thread] %-5level %logger %ndc - %message%newline";
patternLayout.ActivateOptions();

AWSAppender appender = new AWSAppender();
appender.Layout = patternLayout;
appender.LogGroup = Environment.GetEnvironmentVariable("AWS_LAMBDA_LOG_GROUP_NAME");
appender.Region = Environment.GetEnvironmentVariable("AWS_DEFAULT_REGION");
appender.ActivateOptions();

hierarchy.Root.AddAppender(appender);
hierarchy.Root.Level = Level.All;
hierarchy.Configured = true;
LambdaException
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean wrapExceptions, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean skipCheckThis, Boolean fillCache)
Method 'get_ServiceMetadata' in type 'Amazon.CloudWatchLogs.AmazonCloudWatchLogsClient' from assembly 'AWSSDK.CloudWatchLogs, Version=3.3.0.0, Culture=neutral, PublicKeyToken=885c28607f98e604' does not have an implementation.: TypeLoadException
at AWS.Logger.Core.AWSLoggerCore..ctor(AWSLoggerConfig config, String logType)
at AWS.Logger.Log4net.AWSAppender.ActivateOptions()
at ...

Log Entires Not Showing for App running in ECS Container

I have added some basic logging statements to an application. See below for details. This works fine debugging locally. However, when pushing the app out to AWS, building a container in CodeBuild, and running the container on an ECS instance, the entries do not show up. I have other calls to AWS APIs running in the container OK (e.g. SES and SSM).

"AWS.Logging": {
    "Region": "us-west-2",
    "LogGroup": "/app/portal/production",
    "LogLevel": {
      "Default": "Information",
      "System": "Debug",
      "Microsoft": "Debug"
    }
  },
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, MyDbContext dbContext)
{
   //Configure cloudwatch logging
   loggerFactory.AddAWSProvider(Configuration.GetAWSLoggingConfigSection());
   var logger = loggerFactory.CreateLogger<Program>();
   logger.LogInformation(LoggingEvents.ApplicationStart, "Application configuration start");
}

Instance profile policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "kms:Encrypt",
                "kms:Decrypt",
                "kms:ReEncrypt*",
                "kms:GenerateDataKey*",
                "kms:DescribeKey",
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents",
                "logs:DescribeLogStreams",
                "ssm:GetParameter",
                "ses:SendEmail",
                "ses:SendRawEmail"
            ],
            "Resource": "*",
            "Effect": "Allow"
        }
    ]
}

Any ideas on why this would show up in dev and not in release mode running in the container?

Unable to find credentials exception when using latest AWS SDK in ASP.NET Core MVC

I followed configuration procedure in README but I get a "unable to find credentials" exception when calling logerFactory.AddAWSProvider().

According to Configuring the AWS SDK for .NET with .NET Core only a call to AddDefaultAWSOptions(Configuration.GetAWSOptions()) is required in order to automatically detect the profile (and credentials) set in the "AWS" configuration section and inject services in ASP.NET Core MVC. I can confirm that works fine when injecting services in controllers, etc.

It seems like this library is expecting credential values to be also available in "AWS.Logging" section as AWSAccessKey and AWSSecretKey. I imagine these values are used to construct a CloudWatchLogs client somewhere. Why not use the same framework DI facilities used in other parts of the AWSSDK instead and inject the client where needed?

This is the complete stack trace of the exception:

Unable to find credentials

Exception 1 of 3:
Amazon.Runtime.AmazonClientException: Unable to find a default profile in CredentialProfileStoreChain.
at Amazon.Runtime.FallbackCredentialsFactory.GetAWSCredentials(ICredentialProfileSource source, String defaultProfileName) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Credentials\FallbackCredentialsFactory.cs:line 69
at Amazon.Runtime.FallbackCredentialsFactory.GetCredentials(Boolean fallbackToAnonymous) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Credentials\FallbackCredentialsFactory.cs:line 113

Exception 2 of 3:
System.InvalidOperationException: The environment variables AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/AWS_SESSION_TOKEN were not set with AWS credentials.
at Amazon.Runtime.EnvironmentVariablesAWSCredentials.FetchCredentials() in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Credentials_bcl+coreclr\EnvironmentVariablesAWSCredentials.cs:line 80
at Amazon.Runtime.FallbackCredentialsFactory.<>c.b__8_1() in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Credentials\FallbackCredentialsFactory.cs:line 53
at Amazon.Runtime.FallbackCredentialsFactory.GetCredentials(Boolean fallbackToAnonymous) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Credentials\FallbackCredentialsFactory.cs:line 113

Exception 3 of 3:
System.AggregateException: AsyncHelpers.Run method threw an exception. (An error occurred while sending the request.) ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.WinHttpException: Se superó el tiempo de espera para la operación
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at System.Net.Http.WinHttpHandler.<StartRequest>d__105.MoveNext() --- End of inner exception stack trace --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()
at System.Net.Http.HttpClient.d__58.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at System.Net.Http.HttpClient.<GetContentAsync>d__321.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Amazon.Runtime.Internal.Util.AsyncHelpers.<>c__DisplayClass1_01.<<RunSync>b__0>d.MoveNext() in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Internal\Util\_mobile\AsyncHelpers.cs:line 78 --- End of inner exception stack trace --- at Amazon.Runtime.Internal.Util.AsyncHelpers.ExclusiveSynchronizationContext.BeginMessageLoop() in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Internal\Util\_mobile\AsyncHelpers.cs:line 138 at Amazon.Runtime.Internal.Util.AsyncHelpers.RunSync[T](Func1 task) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Internal\Util_mobile\AsyncHelpers.cs:line 86
at Amazon.Util.AWSSDKUtils.DownloadStringContent(Uri uri, TimeSpan timeout) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Util\AWSSDKUtils.cs:line 895
at Amazon.Runtime.URIBasedRefreshingCredentialHelper.GetContents(Uri uri) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Credentials\URIBasedRefreshingCredentialHelper.cs:line 32
at Amazon.Runtime.InstanceProfileAWSCredentials.d__10.MoveNext()
at Amazon.Runtime.InstanceProfileAWSCredentials.GetFirstRole() in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Credentials\InstanceProfileAWSCredentials.cs:line 204
at Amazon.Runtime.FallbackCredentialsFactory.ECSEC2CredentialsWrapper() in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Credentials\FallbackCredentialsFactory.cs:line 92
at Amazon.Runtime.FallbackCredentialsFactory.GetCredentials(Boolean fallbackToAnonymous) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Credentials\FallbackCredentialsFactory.cs:line 113
---> (Inner Exception #0) System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.WinHttpException: Se superó el tiempo de espera para la operación
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at System.Net.Http.WinHttpHandler.<StartRequest>d__105.MoveNext() --- End of inner exception stack trace --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()
at System.Net.Http.HttpClient.d__58.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at System.Net.Http.HttpClient.<GetContentAsync>d__321.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Amazon.Runtime.Internal.Util.AsyncHelpers.<>c__DisplayClass1_0`1.<b__0>d.MoveNext() in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Internal\Util_mobile\AsyncHelpers.cs:line 78<---

Mark AWS.Logger.Core as a dependency of AWS.Logger.NLog?

I followed the instructions on the README for AWS Logging and I was hoping that I could get up and running quite quickly as I've been using the AWSSDK for a quite a while now within my projects.

I installed the package into my project, along with NLog to start logging.

I kept on getting an error message, sporadically:

Target cannot be found: 'AWSTarget'

I was scratching my head, because even with the sample project I wasn't able to get it to run when I deleted the project Nlog.AWS.Logging from the sample project and replaced it with the use of the Nuget package.

After close inspection and playing around with the solution a bit more, adding and removing references and Nuget packages I finally got it to work by installing AWS.Logger.Core into my project.

Install-Package AWS.Logger.Core

Once I did this, it worked perfectly fine and I could see logs in CloudWatch.

I wondered whether this should be added to the documentation for this project, I can't find it in there - I could have missed it though. Also I wondered if the Nuget package AWS.Logger.NLog should have AWS.Logger.Core marked as a dependency?

I have been using the non-modularised AWSSDK, which is if possibly why I was more likely to have fallen into this trap, I'm going to look at moving to the modularised version now.

not sending logs over to cloudwatch

So, I was following the examples and setting up log4net/cloudwatch. But somehow it's not sending logs to cloudwatch. My settings are like this:

cloudwatch1

initiated in global.asax
cloudwatch2

then send exceptions over
cloudwatch3

anyone knows why?

Really appreciate the time and effort of whoever look into this issue.

AWS.Logger.AspNetCore does not respect LogLevels in Lambda

I am using AWS.Logger.AspNetCore (1.2.7) and Aws.Logger.Core(1.1.8)
I followed the websamples example to implement Logging in my Lambda function.
When i run locally i am able to see the logs on console which respects the log levels defined in appsettings.
When the code runs on aws lambda it doesnt respect the AWS.Logging defined in the configs and somehow always shows "INFORMATION" logs and above and ignores all my "DEBUG" logs. Here is what i have in my appsettings

"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"AWS.Logging": {
"Region": "us-east-1",
"LogGroup": "AspNetCore.WebSample",
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}

Support ILogger.BeginScope

Currently, calling ILogger.BeginScope with any value has absolutely no effect. Rather than being discarded, the state should be added as prefix to the message logged inside the scope.

Write into specific log stream?

I have an application with multiple Logger instances. Let's say 3.

image

If I only use Logger 1 everything goes fine but if I jump from Logger 1, Logger 2, Logger 3 this is the result.

image

I want to have 1 log stream per Logger instance.

Is there a way to acomplish this?

For what I can see LogStreamNameSuffix is not enough.

What are the minimum permissions required when log group is already created

Hello,
What are the minimum permissions required when log group is already created?
it is mentioned here that I need the following:
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
"logs:DescribeLogGroups"
but since the group is already created, I expect that:
"logs:CreateLogStream",
"logs:PutLogEvents"
should be enough, tried that but I do n't see any streams logged, any guidance?

The category name probably should be passed to the custom formatter

Including category name in target logs might be useful for metric filters. To prevent breaking existing code the new formatter might use some kind of intermediate object.
While I understand that I probably can work around this with decoration, this might really be useful when collecting detailed logs.

No documentation in the README for Serilog

It would be great to get an example of how to use AWS.Logger.Serilog, it doesn't seem to be included in the README or the samples directory. Next to no examples online either.

Nlog plugin in container not writing logs

We've added the Nlog target to our website to write our log files to cloudwatch.
When run outside a container, everything works perfectly, log groups and logs are written.
When run inside a container or an ecs task (also container), it does not write either.
we have the permissions set up correctly, are there ports that need opened on the container for this to work?
Website is .Net 4.7.1 webforms (not core).
The EC2 instance and task definition have iam roles with a policy with full access to cloudwatch.

How can I apply colon-delimited filter in Clouwatchlogs filter pattern

Hi team,

I am not sure this is the correct place to ask my request. I am trying to put some pattern while passing my Cloudwatch logs to AWS ES. Let's assume my logs look like below lines.

Running:on:http://localhost:8081
Running:on:http://localhost:8081
Running:on:http://localhost:8081
Running:on:http://localhost:8081
Running:on:http://localhost:8081
Running:on:http://localhost:8081

How can I split using colon-delimited filter in AWS Cloudwatch Filter pattern. Kindly someone suggest how to fix this.

Regards,
Raja

Add ITextFormatter to Serilog plugin so can format messages

I’m using the Serilog plugin and want to format by output as JSON. I’ve done the changes locally which work great and are quite small. Basically, I’ve added an ITextFormatter and an optical parameter to the extension methods and then updated the Emit method to use the formatter if one has been passed.

I’d like to get this code back into the project. I’d be grateful if you could let me know how to do this i.e. would you like me to create a pull request?

Cheers,
Rob

web service running in elastic beanstalk is not logging entries to cloudwatch

I have a web server running in Elastic Beanstalk. I configured NLog to log application messages to CloudWatch. When I run the web server locally in localhost (which uses my default credentials), I see the messages from my app logged to CloudWatch. However, when I deploy to Elastic Beanstalk and execute a post request, there is no entry in cloudwatch. What am I missing. The ec2 isntance running the web app uses an IAM role which access policy includes:
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
"logs:DescribeLogGroups"
Any idea what am I missing?

Logging started working with no obvious cause after 4 days of not posting to cloud watch

After setting up a log4net section to my Web.config file

<log4net debug="true">
    <appender name="AWS" type="AWS.Logger.Log4net.AWSAppender,AWS.Logger.Log4net">

      <LogGroup>${CloudwatchLogGroupName}</LogGroup>
      <LogStreamNameSuffix>${CloudwatchLogGroupName}</LogStreamNameSuffix>
      <Region>us-east-1</Region>
      <Profile>${User}</Profile>

      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss}||%-5level||%date{fff}||%message||%logger||%newline" />
      </layout>
    </appender>

    <root>
      <level value="${LogLevel}" />
      <appender-ref ref="AWS" />
    </root>
  </log4net>

and adding the line log4net.Config.XmlConfigurator.Configure() to my Global.asax.cs. Only the log statement directly after that line is logged to CloudWatch then nothing else. That is unless I add the log4net.Config.XmlConfigurator.Configure() line to a different method containing log statements in one of my other files than the logging statements in that function will work and only that function. I had that line in one of my controllers and was only getting logs from a specific function until 4 days later when I started seeing logs from some of my other controllers. I had not changed anything the logs just started appearing. I removed the line and rebuilt and now I'm back to getting that one log after the config line. Has anyone else encountered an issue similar to this?

Expiration on Logs

Is there a way to set the expiration / Delete retention policy for the logs?

Adding credentials to config

Hello,
I've tried creating a default profile but doesn't seem to work. When I try to log something I get this exception:

An unhandled exception occurred and the process was terminated.

Application ID: /LM/W3SVC/2/ROOT

Process ID: 36640

Exception: System.NullReferenceException

Message: Object reference not set to an instance of an object.

StackTrace: at AWS.Logger.Core.AWSLoggerCore.Finalize() in D:\Jenkins\jobs\aws-logging-dotnet\workspace\src\AWS.Logger.Core\Core\AWSLoggerCore.cs:line 146

In the documentation it says "o use a specific AWS credential profile add a Profile under the appender node."

Does anyone have an example of specifying the profile this way?

Also is it possible to add the credentials directly to config without creating a profile? I think the application would be self-contained that way and would work if installed on a new machine. Otherwise some extra configuration on each machine would be required. Maybe I'm missing a point but I think direct credentials in the config would be easier to manage.

Anyway, thanks in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.