public async Task <List <LogEntry> > GetAll(string text)
        {
            using (var client = new AmazonCloudWatchLogsClient(ACCESS_KEY_ID, SECRET_ACCESS_KEY, RegionEndpoint.USEast2))
            {
                //get the log entries for the specified log group and log stream
                var res = await client.GetLogEventsAsync(new GetLogEventsRequest(LOG_GROUP_NAME, LOG_STREAM_NAME));

                //return events from Cloudwatch
                return(res.Events

                       //filter out any that don't match the provided text
                       .Where(r => r.Message.Contains(text))

                       //convert into LogEntry DTO instances
                       .Select(r => new LogEntry()
                {
                    TimeStamp = r.Timestamp, Text = r.Message
                })

                       //provide a list of the above created LogEntry instances
                       .ToList()

                       );
            }
        }
예제 #2
0
        public static LoggerConfiguration AppendAwsCloudwatchLogger(this LoggerConfiguration logger,
                                                                    string logGroupName,
                                                                    string environmentName,
                                                                    LogEventLevel minimumLogEvent)
        {
            logGroupName = $"{logGroupName}/{environmentName}".ToLower();

            var formatter = new CompactJsonFormatter();
            var options   = new CloudWatchSinkOptions
            {
                LogGroupName         = logGroupName,
                TextFormatter        = formatter,
                MinimumLogEventLevel = minimumLogEvent,
                BatchSizeLimit       = 100,
                QueueSizeLimit       = 10000,
                Period                  = TimeSpan.FromSeconds(10),
                CreateLogGroup          = true,
                LogStreamNameProvider   = new DefaultLogStreamProvider(),
                RetryAttempts           = 5,
                LogGroupRetentionPolicy = LogGroupRetentionPolicy.OneDay
            };

            var client = new AmazonCloudWatchLogsClient(RegionEndpoint.SAEast1);

            return(logger
                   //.Filter.ByExcluding(c => c.Properties.Any(p => p.Value.ToString().Contains("swagger")))
                   .WriteTo.AmazonCloudWatch(options, client));
        }
        public AmazonCloudWatchLogsClient InitialiseClient()
        {
            try
            {
                var cloudwatchClient = new AmazonCloudWatchLogsClient(RegionEndpoint.USWest1);

                return(cloudwatchClient);
            }
            catch (AmazonServiceException)
            {
                var lines = System.IO.File.ReadAllLines(@"..\..\..\TestArtifacts\credentials.dec");

                var key    = lines.ElementAt(1);
                var secret = lines.ElementAt(2);

                try
                {
                    var cloudwatchClient = new AmazonCloudWatchLogsClient(new BasicAWSCredentials(key, secret),
                                                                          RegionEndpoint.USWest1);

                    return(cloudwatchClient);
                }
                catch (Exception ex)
                {
                    if (ex.Message.Contains("The security token included in the request is invalid key"))
                    {
                        throw new Exception(string.Format("The security token included in the request is invalid key {0}", key));
                    }
                    throw;
                }
            }
        }
예제 #4
0
        static void ConfigureLogging()
        {
            var selflog = new LoggerConfiguration()
                          .WriteTo.LiterateConsole()
                          .CreateLogger();

            Serilog.Debugging.SelfLog.Enable(msg => selflog.Warning(msg));

            AmazonCloudWatchLogsClient client = null;

            if (credentials != null)
            {
                client = new AmazonCloudWatchLogsClient(credentials, Amazon.RegionEndpoint.USWest2);
            }
            else
            {
                client = new AmazonCloudWatchLogsClient(Amazon.RegionEndpoint.USWest2);
            }

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.AmazonCloudWatch(new CloudWatchSinkOptions
            {
                LogGroupName = "/aaa/test/logging",
                Period       = TimeSpan.FromSeconds(1), // really short only for the purpose of not taking forever
                // BatchSizeLimit = default = 100
            }, client)
                         .CreateLogger();
        }
예제 #5
0
        public static void Handle(bool isProduction, ILoggingBuilder builder, string awsLogGroupName)
        {
            builder.ClearProviders();

            if (!isProduction)
            {
                builder.AddConsole();
            }

            if (string.IsNullOrEmpty(awsLogGroupName))
            {
                return;
            }

            using var cloudwatchLogsClient = new AmazonCloudWatchLogsClient();

            bool logGroupExists = LogGroupExists(cloudwatchLogsClient, awsLogGroupName);

            if (!logGroupExists)
            {
                int days = isProduction ? 30 : 1;
                CreateLogGroup(cloudwatchLogsClient, awsLogGroupName, days);
            }

            var awsLoggerConfig = new AWSLoggerConfig
            {
                LogGroup                = awsLogGroupName,
                BatchPushInterval       = isProduction ? TimeSpan.FromMinutes(1) : TimeSpan.FromSeconds(2),
                DisableLogGroupCreation = true,
                LogStreamNamePrefix     = string.Empty
            };

            builder.AddAWSProvider(awsLoggerConfig, LogLevel.Information);
            Console.WriteLine($"Will write logs to: {awsLogGroupName}");
        }
예제 #6
0
        // snippet-start:[CloudWatchLogs.dotnetv3.DescribeLogGroupsExample]
        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();

            var request = new DescribeLogGroupsRequest
            {
                Limit = 5,
            };

            var response = await client.DescribeLogGroupsAsync(request);

            if (response.LogGroups.Count > 0)
            {
                do
                {
                    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");
                    });
                }while (response.NextToken is not null);
            }
        }
        /// <summary>
        /// Check service health.
        /// </summary>
        /// <param name="client">Instance of <see cref="AmazonCloudWatchLogsClient"/> class.</param>
        /// <returns>Success, RountTripTime.</returns>
        public static async Task <(bool, double)> CheckServiceReachable(AmazonCloudWatchLogsClient client)
        {
            var stopwatch = new Stopwatch();

            try
            {
                stopwatch.Start();
                await client.DescribeLogGroupsAsync(new DescribeLogGroupsRequest
                {
                    LogGroupNamePrefix = "KinesisTap"
                });

                stopwatch.Stop();
            }
            catch (AmazonCloudWatchLogsException)
            {
                stopwatch.Stop();
                // Any exception is fine, we are currently only looking to
                // check if the service is reachable and what is the RTT.
                return(true, stopwatch.ElapsedMilliseconds);
            }
            catch (Exception)
            {
                stopwatch.Stop();
                return(false, stopwatch.ElapsedMilliseconds);
            }

            return(true, stopwatch.ElapsedMilliseconds);
        }
        // snippet-start:[CloudWatchLogs.dotnetv3.CreateExportTaskExample]
        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.");
            }
        }
예제 #9
0
        private static void AwsCloudwatchSinkConfiger(LoggerConfiguration lscf)
        {
            // name of the log group
            var logGroupName = "myLogGroup/dev";

            // options for the sink defaults in https://github.com/Cimpress-MCP/serilog-sinks-awscloudwatch/blob/master/src/Serilog.Sinks.AwsCloudWatch/CloudWatchSinkOptions.cs
            var options = new CloudWatchSinkOptions
            {
                // you must provide a text formatter, otherwise exception throw
                TextFormatter = new Serilog.Formatting.Json.JsonFormatter(),
                // the name of the CloudWatch Log group for logging
                LogGroupName = logGroupName,

                // other defaults defaults
                MinimumLogEventLevel = Serilog.Events.LogEventLevel.Information,
                BatchSizeLimit       = 100,
                QueueSizeLimit       = 10000,
                Period                = TimeSpan.FromSeconds(10),
                CreateLogGroup        = true,
                LogStreamNameProvider = new DefaultLogStreamProvider(),
                RetryAttempts         = 5
            };

            // setup AWS CloudWatch client
            var client = new AmazonCloudWatchLogsClient("yourAwsAccessKey", "yourAwsSecretAccessKey", RegionEndpoint.USWest2);

            lscf.WriteTo
            .AmazonCloudWatch(options, client);
        }
예제 #10
0
        public void Log4Net()
        {
            XmlConfigurator.Configure(new System.IO.FileInfo("log4net.config"));
            logger = LogManager.GetLogger("Log4Net");
            for (int i = 0; i < 10; i++)
            {
                logger.Debug(string.Format("Test logging message {0} Log4Net", i));
            }

            //Added Sleep to give sufficient time for the log stream to get posted on CloudWatch
            Thread.Sleep(10000);
            string region       = "us-west-2";
            string logGroupName = "AWSLog4NetGroupLog4Net";

            AmazonCloudWatchLogsClient client = new AmazonCloudWatchLogsClient(
                Amazon.RegionEndpoint.GetBySystemName(region));

            DescribeLogStreamsResponse describeLogstreamsResponse = client.DescribeLogStreamsAsync(new DescribeLogStreamsRequest
            {
                Descending   = true,
                LogGroupName = logGroupName,
                OrderBy      = "LastEventTime"
            }).Result;


            GetLogEventsResponse getLogEventsResponse = client.GetLogEventsAsync(new GetLogEventsRequest
            {
                LogGroupName  = logGroupName,
                LogStreamName = describeLogstreamsResponse.LogStreams[0].LogStreamName
            }).Result;

            Assert.Equal(10, getLogEventsResponse.Events.Count());
        }
예제 #11
0
        protected override void InitializeTarget()
        {
            base.InitializeTarget();

            var regionConfig = WebConfigurationManager.AppSettings["AWSRegion"] ?? "us-west-1";
            var region       = RegionEndpoint.GetBySystemName(regionConfig);

            try
            {
                var awsClient = new AmazonCloudWatchLogsClient(region);
                var logstream = !string.IsNullOrEmpty(Suffix)
                    ? string.Format("{0}-{1}-{2}", LogStreaam, Environment, Suffix)
                    : !string.IsNullOrEmpty(EC2InstanceMetadata.InstanceId)
                            ? string.Format("{0}-{1}-{2}", LogStreaam, Environment, EC2InstanceMetadata.InstanceId)
                            : string.Format("{0}-{1}", LogStreaam, Environment);

                InternalLogger.Debug("Writing LogStream", logstream);

                _client = new CloudWatchLogsClientWrapper(awsClient, LogGroup, logstream);
                _client.InitialiseLogStream();
            }
            catch (AmazonServiceException ex)
            {
                //purely for runnning it locally for the reason this will be still instantiated even if it's not part of the targe
                if (ex.Message != "Unable to find credentials")
                {
                    throw;
                }
            }
        }
        public static IServiceCollection AddLogger(this IServiceCollection collection, IConfiguration configuration)
        {
            var logConfig = new LoggerConfiguration();
            var sink      = configuration["Logging:Sink"];

            switch (sink)
            {
            case "AWSCloudWatch":
                var accessKeyId           = configuration["AWS:AccessKeyId"];
                var accessSecretAccessKey = configuration["AWS:AccessSecretAccessKey"];

                var client  = new AmazonCloudWatchLogsClient(accessKeyId, accessSecretAccessKey, RegionEndpoint.EUWest2);
                var options = new CloudWatchSinkOptions
                {
                    LogGroupName          = "shared-list-beanstalk-log/ShareListApi-env",
                    Period                = TimeSpan.FromSeconds(10),
                    BatchSizeLimit        = 100,
                    QueueSizeLimit        = 10000,
                    LogStreamNameProvider = new DefaultLogStreamProvider(),
                    RetryAttempts         = 5,
                    CreateLogGroup        = true,
                    TextFormatter         = new AWSTextFormatter(),
                };

                logConfig.WriteTo.AmazonCloudWatch(options, client);
                break;

            default:
                logConfig.WriteTo.RollingFile(Path.Combine(AppContext.BaseDirectory, "log-{Date}.log"));
                break;
            }

            collection.AddSingleton <ILogger>(logConfig.CreateLogger());
            return(collection);
        }
        private List <string> GetLogMessages(string lambdaName)
        {
            var logGroup = GetLogGroup(lambdaName);

            _logsClient = new AmazonCloudWatchLogsClient();

            var logStreams = _logsClient
                             .DescribeLogStreamsAsync(new DescribeLogStreamsRequest(logGroup)).Result
                             .LogStreams;

            var responses = new List <GetLogEventsResponse>();

            foreach (var logStream in logStreams)
            {
                responses.Add(_logsClient.GetLogEventsAsync(new GetLogEventsRequest(logGroup, logStream.LogStreamName)).Result);
            }

            // Each response has many events so
            // simple Select would yield a nested array [[event1, event2,...event99] , [event101, event102,...event199] , [event200, event201,...event299]]
            // SelectMany flattens the array [event1, event2,...event299]]
            var messages = responses.SelectMany(x => x.Events)
                           .Where(x => x.Message.StartsWith("Location:"))
                           .Select(x => x.Message)
                           .ToList();

            return(messages);
        }
예제 #14
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonCloudWatchLogsConfig config = new AmazonCloudWatchLogsConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonCloudWatchLogsClient client = new AmazonCloudWatchLogsClient(creds, config);

            DescribeLogGroupsResponse resp = new DescribeLogGroupsResponse();

            do
            {
                DescribeLogGroupsRequest req = new DescribeLogGroupsRequest
                {
                    NextToken = resp.NextToken
                    ,
                    Limit = maxItems
                };

                resp = client.DescribeLogGroups(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.LogGroups)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
예제 #15
0
        // snippet-start:[CloudWatchLogs.dotnetv3.AssociateKmsKeyExample]
        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}.");
            }
        }
예제 #16
0
        private List <OutputLogEvent> FunctionLogs(string functionName, DateTime start, DateTime end)
        {
            if (_logs == null)
            {
                using (var cwClient = new AmazonCloudWatchLogsClient())
                {
                    var logStreams = new List <LogStream>();
                    DescribeLogStreamsResponse lResponse;
                    string nextToken = null;
                    do
                    {
                        lResponse =
                            cwClient.DescribeLogStreams(new DescribeLogStreamsRequest("/aws/lambda/" + functionName)
                        {
                            NextToken = nextToken
                        });
                        logStreams.AddRange(lResponse.LogStreams);
                    } while (!string.IsNullOrEmpty(nextToken = lResponse.NextToken));
                    List <OutputLogEvent> logs = new List <OutputLogEvent>();
                    logStreams.ForEach(
                        s =>
                        cwClient.GetLogEvents(new GetLogEventsRequest("/aws/lambda/" + functionName,
                                                                      s.LogStreamName)
                    {
                        Limit = 10000
                    }).Events.ForEach(e => logs.Add(e)));
                    _logs = logs;
                }
            }

            return(_logs);
        }
예제 #17
0
        public static void InitLogger(string awsAccessKey, string awsSecretKey, string logName, string streamPrefix = null)
        {
            var logGroupName   = logName;
            var AWS_ACCESS_KEY = awsAccessKey;
            var AWS_SECRET_KEY = awsSecretKey;

            Amazon.RegionEndpoint REGION = Amazon.RegionEndpoint.APSouth1;

            Serilog.Debugging.SelfLog.Enable(Console.WriteLine);
            CloudWatchSinkOptions options = new CloudWatchSinkOptions {
                LogGroupName = logGroupName, LogEventRenderer = new EventLogRenderer()
            };

            if (streamPrefix != null)
            {
                ILogStreamNameProvider streamNameProvider = new ConstantLogStreamNameProvider(streamPrefix);
                options = new CloudWatchSinkOptions {
                    LogGroupName = logGroupName, LogEventRenderer = new EventLogRenderer(), LogStreamNameProvider = streamNameProvider
                };
            }

            // setup AWS CloudWatch client
            AWSCredentials        credentials = new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY);
            IAmazonCloudWatchLogs client      = new AmazonCloudWatchLogsClient(credentials, REGION);


            Log.Logger = new LoggerConfiguration().WriteTo.AmazonCloudWatch(options, client)
                         .MinimumLevel.Verbose()
                         .CreateLogger();
        }
예제 #18
0
        public ConsoleAppTests()
        {
            var cloudFormationClient = new AmazonCloudFormationClient();

            _cloudFormationHelper = new CloudFormationHelper(cloudFormationClient);

            var ecsClient = new AmazonECSClient();

            _ecsHelper = new ECSHelper(ecsClient);

            var cloudWatchLogsClient = new AmazonCloudWatchLogsClient();

            _cloudWatchLogsHelper = new CloudWatchLogsHelper(cloudWatchLogsClient);

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddCustomServices();
            serviceCollection.AddTestServices();

            var serviceProvider = serviceCollection.BuildServiceProvider();

            _app = serviceProvider.GetService <App>();
            Assert.NotNull(_app);

            _interactiveService = serviceProvider.GetService <InMemoryInteractiveService>();
            Assert.NotNull(_interactiveService);

            _testAppManager = new TestAppManager();
        }
예제 #19
0
        /// <summary> Create logger </summary>
        public static ILogger?TryCreateSerilogLogger()
        {
            try
            {
                var logStreamProvider = new DefaultLogStreamProvider();

                var serilogSinkConfig = new CloudWatchSinkOptions
                {
                    LogGroupName          = "Serilog",
                    MinimumLogEventLevel  = LogEventLevel.Information,
                    CreateLogGroup        = false,
                    TextFormatter         = new MessageTemplateTextFormatter("[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"),
                    LogStreamNameProvider = logStreamProvider,
                    RetryAttempts         = 5
                };
                var amazonCloudWatchLogger = new AmazonCloudWatchLogsClient();
                var logger = new LoggerConfiguration()
                             .MinimumLevel.Information()
                             .WriteTo.AmazonCloudWatch(serilogSinkConfig, amazonCloudWatchLogger)
                             .CreateLogger();

                logger.Information("Start");

                return(logger);
            }
            catch
            {
                return(null);
            }
        }
예제 #20
0
        protected virtual void Dispose(bool disposing)
        {
            AmazonCloudWatchLogsClient Client =
                new AmazonCloudWatchLogsClient(Amazon.RegionEndpoint.USWest2);

            foreach (var logGroupName in LogGroupNameList)
            {
                if (!(string.IsNullOrEmpty(logGroupName)))
                {
                    DescribeLogGroupsResponse describeLogGroupsResponse = Client.DescribeLogGroupsAsync(
                        new DescribeLogGroupsRequest
                    {
                        LogGroupNamePrefix = logGroupName
                    }).Result;

                    if (!(string.IsNullOrEmpty(describeLogGroupsResponse.LogGroups[0].LogGroupName)))
                    {
                        var response = Client.DeleteLogGroupAsync(new DeleteLogGroupRequest
                        {
                            LogGroupName = logGroupName
                        }).Result;
                    }
                }
            }
        }
        public async Task DeleteCloudWatchLogStreamsForLogStreams(string logGroupName)
        {
            try
            {
                var client           = new AmazonCloudWatchLogsClient(AwsCredentials, Region);
                var logStreamRequest = new DescribeLogStreamsRequest()
                {
                    LogGroupName = logGroupName,
                    OrderBy      = OrderBy.LastEventTime
                };

                var logStreamsResponse = await client.DescribeLogStreamsAsync(logStreamRequest);  // rate limit is 5 per second

                foreach (var stream in logStreamsResponse.LogStreams)
                {
                    var request = new DeleteLogStreamRequest(logGroupName, stream.LogStreamName);
                    var deleteLogStringresponse = await client.DeleteLogStreamAsync(request);

                    Thread.Sleep(150);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #22
0
        public void ILogger()
        {
            LoggerConfigSectionSetup("appsettings.json", null);
            var logger = LoggerSetup();

            for (int i = 0; i < 10; i++)
            {
                logger.LogDebug(string.Format("Test logging message {0} Ilogger", i));
            }

            //Sleep is introduced to give suffiecient time for the logstream to get posted on CloudWatchLogs
            Thread.Sleep(5000);
            string region       = _configSection.Config.Region;
            string logGroupName = _configSection.Config.LogGroup;

            AmazonCloudWatchLogsClient client = new AmazonCloudWatchLogsClient(
                Amazon.RegionEndpoint.GetBySystemName(region));

            DescribeLogStreamsResponse describeLogstreamsResponse = client.DescribeLogStreamsAsync(new DescribeLogStreamsRequest
            {
                Descending   = true,
                LogGroupName = logGroupName,
                OrderBy      = "LastEventTime"
            }).Result;


            GetLogEventsResponse getLogEventsResponse = client.GetLogEventsAsync(new GetLogEventsRequest
            {
                LogGroupName  = logGroupName,
                LogStreamName = describeLogstreamsResponse.LogStreams[0].LogStreamName
            }).Result;

            Assert.Equal(10, getLogEventsResponse.Events.Count());
        }
예제 #23
0
        // snippet-start:[CloudWatchLogs.dotnetv3.CancelExportTaskExample]
        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.");
            }
        }
        // snippet-start:[CloudWatchLogs.dotnetv3.DescribeExportTasksExammple]
        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);
        }
        // snippet-start:[CloudWatchLogs.dotnetv3.CreateLogGroupExample]
        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.");
            }
        }
예제 #26
0
        public TestFixture()
        {
            AmazonCloudWatchLogsClient Client =
                new AmazonCloudWatchLogsClient(Amazon.RegionEndpoint.USWest2);

            LogGroupNameList = new List <string>();
        }
예제 #27
0
 protected CloudWatchLogger(AmazonCloudWatchLogsClient client, string groupName, string streamName, string sequenceToken = null)
 {
     Client        = client;
     GroupName     = groupName;
     StreamName    = streamName;
     SequenceToken = sequenceToken;
 }
예제 #28
0
        public async Task RegexTest()
        {
            var logGroupName  = "RegexTest";
            var logStreamName = "TestMessage";

            Regex invalid_sequence_token_regex = new
                                                 Regex(@"The given sequenceToken is invalid. The next expected sequenceToken is: (\d+)");

            client = new AmazonCloudWatchLogsClient(RegionEndpoint.USWest2);
            await client.CreateLogGroupAsync(new CreateLogGroupRequest
            {
                LogGroupName = logGroupName
            });

            _testFixure.LogGroupNameList.Add(logGroupName);

            await client.CreateLogStreamAsync(new CreateLogStreamRequest
            {
                LogGroupName  = logGroupName,
                LogStreamName = logStreamName
            });

            var putlogEventsRequest = new PutLogEventsRequest
            {
                LogGroupName  = logGroupName,
                LogStreamName = logStreamName,
                LogEvents     = new List <InputLogEvent>
                {
                    new InputLogEvent
                    {
                        Timestamp = DateTime.Now,
                        Message   = "Message1"
                    }
                }
            };
            var response = await client.PutLogEventsAsync(putlogEventsRequest);

            try
            {
                putlogEventsRequest.LogEvents = new List <InputLogEvent>
                {
                    new InputLogEvent
                    {
                        Timestamp = DateTime.Now,
                        Message   = "Message2"
                    }
                };

                await client.PutLogEventsAsync(putlogEventsRequest);
            }
            catch (InvalidSequenceTokenException ex)
            {
                var regexResult = invalid_sequence_token_regex.Match(ex.Message);

                if (regexResult.Success)
                {
                    Assert.Equal(regexResult.Groups[1].Value, response.NextSequenceToken);
                }
            }
        }
예제 #29
0
        /// <summary>
        /// 创建一个新的日志流并开始记录
        /// </summary>
        /// <param name="client">AWS 客户端</param>
        /// <param name="groupName">日志组名称</param>
        /// <param name="streamName">日志流名称</param>
        /// <returns></returns>
        public static CloudWatchLogger CreateStream(AmazonCloudWatchLogsClient client, string groupName, string streamName)
        {
            var response = client.CreateLogStream(new CreateLogStreamRequest {
                LogGroupName = groupName, LogStreamName = streamName
            });

            return(new CloudWatchLogger(client, groupName, streamName));
        }
예제 #30
0
        void CwLog(string group_name, string stream_name, string body)
        {
            using (var cwl = new AmazonCloudWatchLogsClient(aws_credentials, aws_region))
            {
                int attempts = 0;
                do
                {
                    try
                    {
                        attempts++;
                        var request = new PutLogEventsRequest(group_name, stream_name, new List <InputLogEvent> {
                            new InputLogEvent
                            {
                                Timestamp = DateTime.Now,
                                Message   = body
                            }
                        });
                        request.SequenceToken = cw_logstream_sequence_token;

                        var ret = cwl.PutLogEvents(request);
                        // Update sequence token for next put
                        cw_logstream_sequence_token = ret.NextSequenceToken;
                        break; // success
                    }
                    catch (Amazon.CloudWatchLogs.Model.ResourceNotFoundException e)
                    {
                        Console.WriteLine($"type: {e.ErrorType} code: {e.ErrorCode} source: {e.Source} ");
                        Console.WriteLine(e.Data);

                        CreateCwLogGroup(cw_log_group_name);
                        CreateCwLogSream(cw_log_stream_name);

                        // Log group doesn't exist. Let's create. This only needs to be done once
                        Task.Delay(1000);
                    }
                    catch (Amazon.CloudWatchLogs.Model.InvalidSequenceTokenException e)
                    {
                        // Each log event must contain a sequence value, unless it's the first event
                        // https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/CloudWatchLogs/TPutLogEventsRequest.html
                        cw_logstream_sequence_token = e.ExpectedSequenceToken;
                        // Now that we have the sequence token, try one more time.
                        Console.WriteLine("Exception caught for unexpected squence token. It's now updated and will retry.");
                        Task.Delay(1000);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                        Console.WriteLine("This exception is not handled, will not retry :-( ");
                        break;
                    }
                    if (attempts > 2)
                    {
                        Console.WriteLine("Unable to send log event retries exhausted.");
                        break;
                    }
                } while (true);
            }
        }