[ASP.NET Core] 透過 NLog 將log一併紀錄到 AWS CloudWatch

簡單設定 NLog.config, 即可將log一併紀錄到CloudWatch

環境

  • ASP.NET 5
  • NLog.Web.AspNetCore 4.14.0

nuget

add nuget package AWS.Logger.Nlog

NLog.config

  1. add extensions
  2. add target type AWSTarget, logGroup 及 region 自行設定
<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>

AWS Credential

預設會從路徑 C:\Users\{username}\.aws\credentials 取的AWS的相關連線身分, 若無設定或資訊錯誤, 會在專案目錄中產生log file aws-logger-errors.txt

Log Entry : 
2021/10/16 14:52:35
  :
  :Amazon.Runtime.AmazonServiceException: Unable to get IAM security credentials from EC2 Instance Metadata Service.
   at Amazon.Runtime.DefaultInstanceProfileAWSCredentials.FetchCredentials()
   at Amazon.Runtime.DefaultInstanceProfileAWSCredentials.GetCredentials()
   at Amazon.Runtime.DefaultInstanceProfileAWSCredentials.GetCredentialsAsync()
   at Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.MetricsHandler.InvokeAsync[T](IExecutionContext executionContext)
   at AWS.Logger.Core.AWSLoggerCore.LogEventTransmissionSetup(CancellationToken token)
   at AWS.Logger.Core.AWSLoggerCore.Monitor(CancellationToken token)

參考資料

Aws-logging-dotnet

AWS SDK for .NET

AWS SDK for .NET file path