

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用在 Amazon Logs 中为.NET 应用程序配置 CloudWatch 日志记录 NLog
<a name="configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog"></a>

*Bibhuti Sahu 和 Rob Hill（AWS），Amazon Web Services*

## Summary
<a name="configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog-summary"></a>

此模式描述了如何使用 NLog 开源日志框架在 [Amazon Log CloudWatch s](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html) 中记录.NET 应用程序的使用情况和事件。在 CloudWatch 控制台中，您可以近乎实时地查看应用程序的日志消息。您还可以设置[指标](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/MonitoringLogData.html)并配置[警报](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ConsoleAlarms.html)，以便在超过指标阈值时通知您。使用 A CloudWatch pplication Insights，您可以查看显示受监控应用程序潜在问题的自动或自定义仪表板。 CloudWatch Application Insights 旨在帮助您快速隔离应用程序和基础架构中持续存在的问题。

要将日志消息写入 CloudWatch 日志，请将`AWS.Logger.NLog` NuGet 软件包添加到.NET 项目中。然后，更新`NLog.config`文件以使用 CloudWatch 日志作为目标。

## 先决条件和限制
<a name="configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account。
+ 一个 .NET Web 或控制台应用程序，它可以：
  + 使用支持的 .NET 框架或 .NET 核心版本。有关更多信息，请参阅*产品版本*。
  + 用于向 A NLog pplication Insights 发送日志数据。
+ 为 Amazon Web Services 创建 IAM 角色的权限。有关更多信息，请参阅[服务角色权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html#id_roles_create_service-permissions)。
+ 将角色传递给服务的权限。有关更多信息，请参阅[向用户授予将角色传递给 Amazon Web Services 的权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html)。

**产品版本**
+ .NET Framework 版本 3.5 或更高版本
+ .NET Core 版本 1.0.1、2.0.0 或更高版本

## 架构
<a name="configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog-architecture"></a>

**目标技术堆栈**
+ NLog
+ Amazon CloudWatch 日志

**目标架构**

![将.NET 应用程序的日志数据 NLog 写入 Amazon Lo ClodWatch gs 的架构图。](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/0ac9c3ad-2a28-415f-afc3-7fe3494b2b63/images/daea9f2f-7242-4ed2-843e-655d843dcfdf.png)


1. .NET 应用程序将日志数据写入 NLog 日志框架。

1. NLog 将日志数据写入 CloudWatch 日志。

1. 您可以使用 CloudWatch 警报和自定义仪表板来监控.NET 应用程序。

## 工具
<a name="configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog-tools"></a>

**AWS 服务**
+ [Amazon App CloudWatch lication Insights](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html) 可帮助您观察应用程序和底层 AWS 资源的运行状况。
+ [Amazon CloudWatch Lo](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html) gs 可帮助您集中管理来自所有系统、应用程序和 AWS 服务的日志，以便您可以监控它们并安全地将其存档。
+ [AWS Identity and Access Management (AWS IAM) ](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)通过控制验证和授权使用您 AWS 资源的用户，帮助您安全地管理对您 AWS 资源的访问。
+ [AWS 工具 PowerShell](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-welcome.html)是一组 PowerShell 模块，可帮助您通过 PowerShell 命令行编写对 AWS 资源的操作的脚本。

**其他工具**
+ [记录器。 NLog](https://www.nuget.org/packages/AWS.Logger.NLog)是将日志数据记录到 CloudWatch 日志的 NLog 目标。
+ [NLog](https://nlog-project.org/)是适用于.NET 平台的开源日志框架，可帮助您将日志数据写入目标，例如数据库、日志文件或控制台。
+ [PowerShell](https://learn.microsoft.com/en-us/powershell/)是一款在 Windows、Linux 和 macOS 上运行的微软自动化和配置管理程序。
+ [Visual Studio](https://docs.microsoft.com/en-us/visualstudio/get-started/visual-studio-ide?view=vs-2022) 是一个集成式开发环境（IDE），包括编译器、代码完成工具、图形设计器和其他支持软件开发的功能。

## 最佳实践
<a name="configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog-best-practices"></a>
+ 为目标日志组设置[保留策略](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html#SettingLogRetention)。这必须在 NLog 配置之外完成。默认情况下，日志数据无限期地存储在 CloudWatch 日志中。
+ 坚持[管理 AWS 访问密钥的最佳实践](https://docs.aws.amazon.com/accounts/latest/reference/credentials-access-keys-best-practices.html)。

## 操作说明
<a name="configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog-epics"></a>

### 设置访问权限和工具
<a name="set-up-access-and-tools"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建一个 IAM 策略。 | 按照 IAM 文档中[使用 JSON 编辑器创建策略](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create-console.html#access_policies_create-json-editor)中的说明进行操作。输入以下 JSON 策略，该策略具有允许 CloudWatch 日志读取和写入日志所需的最低权限。<pre>{<br />    "Version": "2012-10-17",		 	 	 <br />    "Statement": [<br />        {<br />            "Effect": "Allow",<br />            "Action": [<br />                "logs:CreateLogGroup",<br />                "logs:CreateLogStream",<br />                "logs:GetLogEvents",<br />                "logs:PutLogEvents",<br />                "logs:DescribeLogGroups",<br />                "logs:DescribeLogStreams",<br />                "logs:PutRetentionPolicy"<br />            ],<br />            "Resource": [<br />                "*"<br />            ]<br />        }<br />    ]<br />}</pre> | AWS 管理员，AWS DevOps | 
| 创建 IAM 角色。 | 请按照 IAM 文档中的[创建向 Amazon Web Services 委托权限的角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html)说明进行操作。选择您之前创建的策略。这是 Logs 在执行 CloudWatch 日志操作时扮演的角色。 | AWS 管理员，AWS DevOps | 
| 为其设置 AWS 工具 PowerShell。 | [See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog.html) | 常规 AWS | 

### 配置 NLog
<a name="configure-nlog"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装 NuGet 软件包。 | [See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog.html) | 应用程序开发人员 | 
| 配置日志目标。 | [See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog.html)有关示例配置文件，请参阅此模式的[其他信息](#configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog-additional)部分。运行应用程序时， NLog 将写入日志消息并将其发送到 Lo CloudWatch gs。 | 应用程序开发人员 | 

### 验证和监控日志
<a name="validate-and-monitor-logs"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证日志记录。 | 按照 “日志” 文档中[查看发送到 CloudWatch 日志的日志数据](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html#ViewingLogData)中的 CloudWatch 说明进行操作。验证是否正在记录 .NET 应用程序的日志事件。如果未记录日志事件，请参阅此模式中的[故障排除](#configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog-troubleshooting)部分。 | 常规 AWS | 
| 监控 .NET 应用程序堆栈。 | 根据您的用例 CloudWatch 的需要在中配置监控。您可以使用 “[CloudWatch 日志见解](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html)”、“[CloudWatch 指标见解](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/query_with_cloudwatch-metrics-insights.html)” 和 “[CloudWatch 应用程序见解](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html)” 来监控您的.NET 工作负载。您还可以配置[警报](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html)以接收警报，还可以创建用于从单一视图监控工作负载的自定义[控制面板](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html)。 | 常规 AWS | 

## 问题排查
<a name="configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 日志数据不会显示在 CloudWatch 日志中。 | 确保将 IAM 策略附加到 L CloudWatch ogs 担任的 IAM 角色。有关说明，请参阅[操作说明](#configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog-epics)部分的*设置访问权限和工具*部分。 | 

## 相关资源
<a name="configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog-resources"></a>
+ [使用日志组和日志流](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html)（CloudWatch 日志文档）
+ [Amazon CloudWatch 日志和.NET 日志框架](https://aws.amazon.com/blogs/developer/amazon-cloudwatch-logs-and-net-logging-frameworks/)（AWS 博客文章）

## 附加信息
<a name="configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog-additional"></a>

以下为示例 `NLog.config` 文件。

```
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
  </startup>
  <nlog>
    <extensions>
      <add assembly="NLog.AWS.Logger" />
    </extensions>
    <targets>
      <target name="aws" type="AWSTarget" logGroup="NLog.TestGroup" region="us-east-1" profile="demo"/>
    </targets>
    <rules>
      <logger name="*" minlevel="Info" writeTo="aws" />
    </rules>    
  </nlog>
</configuration>
```