CloudWatch 使用记录示例 AWS SDK for .NET - AWS SDK 代码示例

AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例

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

CloudWatch 使用记录示例 AWS SDK for .NET

以下代码示例向您展示了如何使用 with Logs 来执行操作和实现常见场 CloudWatch 景。 AWS SDK for .NET

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景和跨服务示例的上下文查看操作。

场景是展示如何通过在同一服务中调用多个函数来完成特定任务任务的代码示例。

每个示例都包含一个指向的链接 GitHub,您可以在其中找到有关如何在上下文中设置和运行代码的说明。

主题

操作

以下代码示例演示如何使用 AssociateKmsKey

AWS SDK for .NET
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

using System; using System.Threading.Tasks; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; /// <summary> /// Shows how to associate an AWS Key Management Service (AWS KMS) key with /// an Amazon CloudWatch Logs log group. /// </summary> public class AssociateKmsKey { public static async Task Main() { // This client object will be associated with the same AWS Region // as the default user on this system. If you need to use a // different AWS Region, pass it as a parameter to the client // constructor. var client = new AmazonCloudWatchLogsClient(); string kmsKeyId = "arn:aws:kms:us-west-2:<account-number>:key/7c9eccc2-38cb-4c4f-9db3-766ee8dd3ad4"; string groupName = "cloudwatchlogs-example-loggroup"; var request = new AssociateKmsKeyRequest { KmsKeyId = kmsKeyId, LogGroupName = groupName, }; var response = await client.AssociateKmsKeyAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine($"Successfully associated KMS key ID: {kmsKeyId} with log group: {groupName}."); } else { Console.WriteLine("Could not make the association between: {kmsKeyId} and {groupName}."); } } }
  • 有关API详细信息,请参阅 “AWS SDK for .NET API参考 AssociateKmsKey” 中的。

以下代码示例演示如何使用 CancelExportTask

AWS SDK for .NET
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

using System; using System.Threading.Tasks; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; /// <summary> /// Shows how to cancel an Amazon CloudWatch Logs export task. /// </summary> public class CancelExportTask { public static async Task Main() { // This client object will be associated with the same AWS Region // as the default user on this system. If you need to use a // different AWS Region, pass it as a parameter to the client // constructor. var client = new AmazonCloudWatchLogsClient(); string taskId = "exampleTaskId"; var request = new CancelExportTaskRequest { TaskId = taskId, }; var response = await client.CancelExportTaskAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine($"{taskId} successfully canceled."); } else { Console.WriteLine($"{taskId} could not be canceled."); } } }
  • 有关API详细信息,请参阅 “AWS SDK for .NET API参考 CancelExportTask” 中的。

以下代码示例演示如何使用 CreateExportTask

AWS SDK for .NET
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

using System; using System.Threading.Tasks; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; /// <summary> /// Shows how to create an Export Task to export the contents of the Amazon /// CloudWatch Logs to the specified Amazon Simple Storage Service (Amazon S3) /// bucket. /// </summary> public class CreateExportTask { public static async Task Main() { // This client object will be associated with the same AWS Region // as the default user on this system. If you need to use a // different AWS Region, pass it as a parameter to the client // constructor. var client = new AmazonCloudWatchLogsClient(); string taskName = "export-task-example"; string logGroupName = "cloudwatchlogs-example-loggroup"; string destination = "doc-example-bucket"; var fromTime = 1437584472382; var toTime = 1437584472833; var request = new CreateExportTaskRequest { From = fromTime, To = toTime, TaskName = taskName, LogGroupName = logGroupName, Destination = destination, }; var response = await client.CreateExportTaskAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine($"The task, {taskName} with ID: " + $"{response.TaskId} has been created successfully."); } } }
  • 有关API详细信息,请参阅 “AWS SDK for .NET API参考 CreateExportTask” 中的。

以下代码示例演示如何使用 CreateLogGroup

AWS SDK for .NET
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

using System; using System.Threading.Tasks; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; /// <summary> /// Shows how to create an Amazon CloudWatch Logs log group. /// </summary> public class CreateLogGroup { public static async Task Main() { // This client object will be associated with the same AWS Region // as the default user on this system. If you need to use a // different AWS Region, pass it as a parameter to the client // constructor. var client = new AmazonCloudWatchLogsClient(); string logGroupName = "cloudwatchlogs-example-loggroup"; var request = new CreateLogGroupRequest { LogGroupName = logGroupName, }; var response = await client.CreateLogGroupAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine($"Successfully create log group with ID: {logGroupName}."); } else { Console.WriteLine("Could not create log group."); } } }
  • 有关API详细信息,请参阅 “AWS SDK for .NET API参考 CreateLogGroup” 中的。

以下代码示例演示如何使用 CreateLogStream

AWS SDK for .NET
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

using System; using System.Threading.Tasks; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; /// <summary> /// Shows how to create an Amazon CloudWatch Logs stream for a CloudWatch /// log group. /// </summary> public class CreateLogStream { public static async Task Main() { // This client object will be associated with the same AWS Region // as the default user on this system. If you need to use a // different AWS Region, pass it as a parameter to the client // constructor. var client = new AmazonCloudWatchLogsClient(); string logGroupName = "cloudwatchlogs-example-loggroup"; string logStreamName = "cloudwatchlogs-example-logstream"; var request = new CreateLogStreamRequest { LogGroupName = logGroupName, LogStreamName = logStreamName, }; var response = await client.CreateLogStreamAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine($"{logStreamName} successfully created for {logGroupName}."); } else { Console.WriteLine("Could not create stream."); } } }
  • 有关API详细信息,请参阅 “AWS SDK for .NET API参考 CreateLogStream” 中的。

以下代码示例演示如何使用 DeleteLogGroup

AWS SDK for .NET
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

using System; using System.Threading.Tasks; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; /// <summary> /// Uses the Amazon CloudWatch Logs Service to delete an existing /// CloudWatch Logs log group. /// </summary> public class DeleteLogGroup { public static async Task Main() { var client = new AmazonCloudWatchLogsClient(); string logGroupName = "cloudwatchlogs-example-loggroup"; var request = new DeleteLogGroupRequest { LogGroupName = logGroupName, }; var response = await client.DeleteLogGroupAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine($"Successfully deleted CloudWatch log group, {logGroupName}."); } } }
  • 有关API详细信息,请参阅 “AWS SDK for .NET API参考 DeleteLogGroup” 中的。

以下代码示例演示如何使用 DescribeExportTasks

AWS SDK for .NET
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

using System; using System.Threading.Tasks; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; /// <summary> /// Shows how to retrieve a list of information about Amazon CloudWatch /// Logs export tasks. /// </summary> public class DescribeExportTasks { public static async Task Main() { // This client object will be associated with the same AWS Region // as the default user on this system. If you need to use a // different AWS Region, pass it as a parameter to the client // constructor. var client = new AmazonCloudWatchLogsClient(); var request = new DescribeExportTasksRequest { Limit = 5, }; var response = new DescribeExportTasksResponse(); do { response = await client.DescribeExportTasksAsync(request); response.ExportTasks.ForEach(t => { Console.WriteLine($"{t.TaskName} with ID: {t.TaskId} has status: {t.Status}"); }); } while (response.NextToken is not null); } }
  • 有关API详细信息,请参阅 “AWS SDK for .NET API参考 DescribeExportTasks” 中的。

以下代码示例演示如何使用 DescribeLogGroups

AWS SDK for .NET
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

using System; using System.Threading.Tasks; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; /// <summary> /// Retrieves information about existing Amazon CloudWatch Logs log groups /// and displays the information on the console. /// </summary> public class DescribeLogGroups { public static async Task Main() { // Creates a CloudWatch Logs client using the default // user. If you need to work with resources in another // AWS Region than the one defined for the default user, // pass the AWS Region as a parameter to the client constructor. var client = new AmazonCloudWatchLogsClient(); bool done = false; string newToken = null; var request = new DescribeLogGroupsRequest { Limit = 5, }; DescribeLogGroupsResponse response; do { if (newToken is not null) { request.NextToken = newToken; } response = await client.DescribeLogGroupsAsync(request); response.LogGroups.ForEach(lg => { Console.WriteLine($"{lg.LogGroupName} is associated with the key: {lg.KmsKeyId}."); Console.WriteLine($"Created on: {lg.CreationTime.Date.Date}"); Console.WriteLine($"Date for this group will be stored for: {lg.RetentionInDays} days.\n"); }); if (response.NextToken is null) { done = true; } else { newToken = response.NextToken; } } while (!done); } }
  • 有关API详细信息,请参阅 “AWS SDK for .NET API参考 DescribeLogGroups” 中的。

以下代码示例演示如何使用 StartLiveTail

AWS SDK for .NET

包含所需的文件。

using Amazon; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model;

启动 Live Tail 会话

var client = new AmazonCloudWatchLogsClient(); var request = new StartLiveTailRequest { LogGroupIdentifiers = logGroupIdentifiers, LogStreamNames = logStreamNames, LogEventFilterPattern = filterPattern, }; var response = await client.StartLiveTailAsync(request); // Catch if request fails if (response.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("Failed to start live tail session"); return; }

您可以通过两种方式处理 Live Tail 会话中的事件:

/* Method 1 * 1). Asynchronously loop through the event stream * 2). Set a timer to dispose the stream and stop the Live Tail session at the end. */ var eventStream = response.ResponseStream; var task = Task.Run(() => { foreach (var item in eventStream) { if (item is LiveTailSessionUpdate liveTailSessionUpdate) { foreach (var sessionResult in liveTailSessionUpdate.SessionResults) { Console.WriteLine("Message : {0}", sessionResult.Message); } } if (item is LiveTailSessionStart) { Console.WriteLine("Live Tail session started"); } // On-stream exceptions are processed here if (item is CloudWatchLogsEventStreamException) { Console.WriteLine($"ERROR: {item}"); } } }); // Close the stream to stop the session after a timeout if (!task.Wait(TimeSpan.FromSeconds(10))){ eventStream.Dispose(); Console.WriteLine("End of line"); }
/* Method 2 * 1). Add event handlers to each event variable * 2). Start processing the stream and wait for a timeout using AutoResetEvent */ AutoResetEvent endEvent = new AutoResetEvent(false); var eventStream = response.ResponseStream; using (eventStream) // automatically disposes the stream to stop the session after execution finishes { eventStream.SessionStartReceived += (sender, e) => { Console.WriteLine("LiveTail session started"); }; eventStream.SessionUpdateReceived += (sender, e) => { foreach (LiveTailSessionLogEvent logEvent in e.EventStreamEvent.SessionResults){ Console.WriteLine("Message: {0}", logEvent.Message); } }; // On-stream exceptions are captured here eventStream.ExceptionReceived += (sender, e) => { Console.WriteLine($"ERROR: {e.EventStreamException.Message}"); }; eventStream.StartProcessing(); // Stream events for this amount of time. endEvent.WaitOne(TimeSpan.FromSeconds(10)); Console.WriteLine("End of line"); }
  • 有关API详细信息,请参阅 “AWS SDK for .NET API参考 StartLiveTail” 中的。