将CloudWatch配置为NLog

时间:2017-08-23 09:26:32

标签: c# .net amazon-web-services nlog amazon-cloudwatch

我一直在尝试将cloudwatch设置为.Net应用程序中的Nlog框架的目标。他们没有提及他们关于此的文件。

这是我的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">
<targets>
  <target name="aws" type="AWSTarget" logGroup="NLog.ConfigExample" region="us-east-1"/>
  <target name="logfile" xsi:type="Console" layout="${callsite} ${message}"/>
</targets>
<rules>
   <logger name="*" minlevel="Info" writeTo="logfile,aws" />
</rules
</nlog>

正如他们的示例项目所说,没有什么重要的。我已经在我的环境变量中设置了AWS凭证。

我已经在云监视中创建了一个logGroup

1 个答案:

答案 0 :(得分:2)

这适用于.NET Core应用程序。

using Microsoft.Extensions.Options;
using NLog;
using NLog.AWS.Logger;
using NLog.Config;
using NLog.Layouts;
using System;

namespace AAAA.BBBB.CCCC
{
    public interface ILogger
    {
        void LogError(string message);
        void LogError(string message, Exception exception);
        void LogInformation(string message);
    }

    public class Logger : ILogger
    {
        private static readonly NLog.Logger _logger = LogManager.GetCurrentClassLogger();

        public Logger(IOptions<AppSettings> appSettings)
        {
            var awsSettings = appSettings.Value.AwsSettings;

            var awsTarget = new AWSTarget()
            {
                LogGroup = awsSettings.CloudWatchLogGroup,
                Region = awsSettings.Region,
                Credentials = new Amazon.Runtime.BasicAWSCredentials(awsSettings.AccessId, awsSettings.AccessKey),
                Layout = new SimpleLayout
                {
                    Text = "${longdate} ${level:uppercase=true} ${machinename} ${message} ${exception:format=tostring}"
                }
            };

            var config = new LoggingConfiguration();
            config.AddTarget("aws", awsTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, awsTarget));
            LogManager.Configuration = config;
        }

        public void LogError(string message)
        {
            _logger.Error(message);
        }

        public void LogError(string message, Exception exception)
        {
            _logger.Error(exception, message);
        }

        public void LogInformation(string message)
        {
            _logger.Info(message);
        }
    }

    public class AppSettings
    {
        public AwsSettings AwsSettings { get; set; }
    }

    public class AwsSettings
    {
        public string AccessId { get; set; } = default!;
        public string AccessKey { get; set; } = default!;
        public string CloudWatchLogGroup { get; set; } = default!;
        public string Region { get; set; } = default!;
    }
}