Wednesday, January 11, 2023

AWS Cloud Watch

 using Amazon.CloudWatchLogs;

using Amazon.CloudWatchLogs.Model;

using Amazon.Runtime;

using API_Infrastructure.DBHelpers;

using API_Infrastructure.Interfaces;

using API_Models.dbModels;

using System;

using System.Collections.Generic;

using System.Configuration;

using System.Linq;

using System.Threading.Tasks;


namespace API_Infrastructure.Helper

{

    public class CloudWatcherLogger

    {

        private string LogMode;

        private string LogGroupName;

        private AmazonCloudWatchLogsClient LogClient;

        private string _nextSequenceToken = null;

        private string _logStream;

        private string accessKey = ConfigurationManager.AppSettings["AccessKey"];

        private string secretKey = ConfigurationManager.AppSettings["SecretKey"];

        private string regionName = ConfigurationManager.AppSettings["RegionName"];


        public CloudWatcherLogger()

        {

            this.LogMode = ConfigurationManager.AppSettings["LogMode"] ?? "DB";

            this.LogGroupName = ConfigurationManager.AppSettings["LogGroupName"] ?? "/development/opensparkz/logs";

            this.LogClient = new AmazonCloudWatchLogsClient();

        }



        public static CloudWatcherLogger GetLogger()

        {

            var logger = new CloudWatcherLogger();


            // Create a log group for our logger

            logger.CreateLogGroup();


            // Create a log stream

            logger.CreateLogStream();


            return logger;

        }



        /// <summary>

        /// Logs the data into cloud watch.

        /// </summary>

        /// <param name="json">String json to log.</param>

        public async Task LogData(string json)

        {

            try

            {

                var response = await this.LogClient.PutLogEventsAsync(new PutLogEventsRequest()

                {

                    LogGroupName = this.LogGroupName,

                    LogStreamName = _logStream,

                    LogEvents = new List<InputLogEvent>()

                                {

                                    new InputLogEvent()

                                    {

                                        Message = json,

                                        Timestamp = DateTime.UtcNow

                                    }

                                },

                    SequenceToken = _nextSequenceToken

                });


                this._nextSequenceToken = response.NextSequenceToken;

            }

            catch (Exception)

            {

            }

        }


        private void CreateLogStream()

        {

            this._logStream = DateTime.UtcNow.ToString("yyyyMMddHHmmssfff");

            this.LogClient.CreateLogStream(new CreateLogStreamRequest(this.LogGroupName, this._logStream));

        }


        private void CreateLogGroup()

        {

            try

            {

                var existing = this.LogClient.DescribeLogGroups(new DescribeLogGroupsRequest() { LogGroupNamePrefix = this.LogGroupName });

                var logGroupExists = existing.LogGroups.Any(l => l.LogGroupName == this.LogGroupName);

                if (!logGroupExists)

                    this.LogClient.CreateLogGroup(new CreateLogGroupRequest(this.LogGroupName));

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

    }

}

No comments: