/// <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));
        }
        bool CreateCwLogSream(string stream_name)
        {
            using (var cwl = new AmazonCloudWatchLogsClient(aws_credentials, aws_region))
            {
                try
                {
                    Console.WriteLine($"Creating log stream {stream_name}.");
                    cwl.CreateLogStream(new CreateLogStreamRequest(cw_log_group_name, cw_log_stream_name));
                    return(true);
                }

                catch
                {
                    return(false);
                }
            }
        }
Exemple #3
0
        static void Main(string[] args)
        {
            var logClient = new AmazonCloudWatchLogsClient();
            // Add a new log group for testing
            const string newLogGroupName   = "NewLogGroup";
            DescribeLogGroupsResponse dlgr = logClient.DescribeLogGroups();
            var groups = new List <LogGroup> {
            };

            groups = dlgr.LogGroups;
            LogGroup lg = new LogGroup();

            lg.LogGroupName = newLogGroupName;
            // Look for our new log group name to determine if we need to do setup
            LogGroup result = groups.Find(
                delegate(LogGroup bk)
            {
                return(bk.LogGroupName == newLogGroupName);
            }
                );

            if (result != null)
            {
                Console.WriteLine(result.LogGroupName + " found");
            }
            else
            {
                //Haven't seen this log group, set it up
                CreateLogGroupRequest clgr = new CreateLogGroupRequest(newLogGroupName);
                logClient.CreateLogGroup(clgr);
                // Create a file to sace next SequenceToken in
                File.CreateText("..\\..\\" + lg.LogGroupName + ".txt");
                CreateLogStreamRequest csr = new CreateLogStreamRequest(lg.LogGroupName, newLogGroupName);
                logClient.CreateLogStream(csr);
            }

            string tokenFile = "";

            try
            {
                Console.WriteLine(lg.LogGroupName);
                //Pick up the next sequence token from the last run
                tokenFile = lg.LogGroupName;
                StreamReader sr            = File.OpenText("..\\..\\" + tokenFile + ".txt");
                string       sequenceToken = sr.ReadLine();
                sr.Close();
                lg.RetentionInDays = 30;
                string groupName                  = lg.LogGroupName;;
                TestMetricFilterRequest tmfr      = new TestMetricFilterRequest();
                List <InputLogEvent>    logEvents = new List <InputLogEvent>(3);
                InputLogEvent           ile       = new InputLogEvent();
                ile.Message = "Test Event 1";
                //DateTime dt = new DateTime(1394793518000);
                DateTime dt = new DateTime(2017, 01, 11);
                ile.Timestamp = dt;
                logEvents.Add(ile);
                ile.Message = "Test Event 2";
                logEvents.Add(ile);
                ile.Message = "This message also contains an Error";
                logEvents.Add(ile);
                DescribeLogStreamsRequest dlsr = new DescribeLogStreamsRequest(groupName);

                PutLogEventsRequest pler = new PutLogEventsRequest(groupName, tokenFile, logEvents);
                pler.SequenceToken = sequenceToken; //use last sequence token
                PutLogEventsResponse plerp = new PutLogEventsResponse();
                plerp = logClient.PutLogEvents(pler);
                Console.WriteLine("Next sequence token = " + plerp.NextSequenceToken);
                FileStream fs = File.OpenWrite("..\\..\\" + tokenFile + ".txt");
                fs.Position = 0;
                UTF8Encoding utf8         = new UTF8Encoding();
                Byte[]       encodedBytes = utf8.GetBytes(plerp.NextSequenceToken);
                fs.Write(encodedBytes, 0, utf8.GetByteCount(plerp.NextSequenceToken));
                fs.Close();
                List <string> lem = new List <string>(1);
                lem.Add("Error");
                tmfr.LogEventMessages = lem;
                tmfr.FilterPattern    = "Error";
                TestMetricFilterResponse tmfrp = new TestMetricFilterResponse();
                tmfrp = logClient.TestMetricFilter(tmfr);
                var results = new List <MetricFilterMatchRecord> {
                };
                results = tmfrp.Matches;
                Console.WriteLine("Found " + results.Count.ToString() + " match records");
                IEnumerator ie = results.GetEnumerator();
                while (ie.MoveNext())
                {
                    MetricFilterMatchRecord mfmr = (MetricFilterMatchRecord)ie.Current;
                    Console.WriteLine("Event Message = " + mfmr.EventMessage);
                }
                Console.WriteLine("Metric filter test done");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        void Writer(object sender, ElapsedEventArgs e)
        {
            var logEvents = new List <InputLogEvent>();

            try
            {
                var more = true;
                while (more)
                {
                    InputLogEvent item;
                    more = items.TryTake(out item);
                    if (more)
                    {
                        logEvents.Add(item);
                    }
                }

                if (logEvents.Count == 0)
                {
                    return;
                }

                if (!Settings.Default.SendUsageData)
                {
                    return;
                }

                using (var logs = new AmazonCloudWatchLogsClient(AwsKeys.AccessKey, AwsKeys.SecretKey, RegionEndpoint.APSoutheast2))
                {
                    var request = new PutLogEventsRequest(AwsKeys.GroupName, LogStreamName, logEvents);

                    var describeLogStreamsRequest = new DescribeLogStreamsRequest(AwsKeys.GroupName)
                    {
                        LogStreamNamePrefix = trackingId,
                        Descending          = true
                    };
                    var describeLogStreamsResponse = logs.DescribeLogStreams(describeLogStreamsRequest);
                    var logStreams = describeLogStreamsResponse.LogStreams;
                    var logStream  = logStreams.FirstOrDefault(ls => ls.LogStreamName == LogStreamName);
                    if (logStream != null)
                    {
                        var token = logStream.UploadSequenceToken;
                        request.SequenceToken = token;
                        checkResponse(logs.PutLogEvents(request));
                    }
                    else
                    {
                        var createRequest = new CreateLogStreamRequest(AwsKeys.GroupName, LogStreamName);
                        checkResponse(logs.CreateLogStream(createRequest));
                        checkResponse(logs.PutLogEvents(request));
                    }
                }
            }
            catch (Exception ee)
            {
                AttempToRestoreErrors(logEvents, ee);
            }
            finally
            {
                if (timer != null)
                {
                    timer.Start();
                }
            }
        }