Skip to content

Instantly share code, notes, and snippets.

@akira345
Last active October 6, 2019 23:00
Show Gist options
  • Save akira345/8923e3c4ff1592703edac39f1fe1c989 to your computer and use it in GitHub Desktop.
Save akira345/8923e3c4ff1592703edac39f1fe1c989 to your computer and use it in GitHub Desktop.
ラムダでエラーが発生した場合、CloudWatchLogsを検索してSNSに通知する。(要AWS SDK for Ruby V3)
# frozen_string_literal: true
source "https://rubygems.org"
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
# gem "rails"
gem 'aws-sdk', '~> 3'
gem "activesupport"
# -*- coding: utf-8 -*-
# frozen_string_literal: true
#
# https://qiita.com/onooooo/items/f59c69e30dc5b477f9fd よりRubyに移植し、全CloudWatchLogsからロググループを探索するように修正。
#
require 'aws-sdk'
require 'json'
require 'time'
require 'active_support/core_ext'
# SNSトピックのARN
TOPIC_ARN = 'arn:aws:sns:ap-northeast-1:0123456789:SendEmail_Lambda_Alert_TOPIC_NAME'
# 抽出するログデータの最大件数
OUTPUT_LIMIT = 5
# 何分前までを抽出対象期間とするか
TIME_FROM_MIN = 10
def lambda_handler(event, context)
print event
message = event['Records'][0]['Sns']['Message']
print 'SNS Message:' + message
message = JSON.parse(message)
message['AlarmDescription'] ||= ''
print message
print 'step1'
begin
logs = Aws::CloudWatchLogs::Client.new(
region: 'ap-northeast-1'
)
print message['Trigger']['MetricName']
print message['Trigger']['NameSpace']
logs.describe_log_groups({
log_group_name_prefix: '/aws/lambda/'
}).each_page do |resp|
log_groups = resp['logGroups']
print log_groups
log_groups.each do |log_group|
print 'step2'
# "StateChangeTime": "2019-10-02T03:06:09.551+0000"
timeto = Time.strptime(message['StateChangeTime'][0, 19], '%Y-%m-%dT%H:%M:%S').since(1.minute)
u_to = timeto.to_i * 1000
timefrom = timeto.ago(TIME_FROM_MIN.minutes)
u_from = timefrom.to_i * 1000
print 'step3'
logs.filter_log_events({
logGroupName: log_group['logGroupName'] ,
filterPattern: 'Error',
startTime: u_from,
endTime: u_to,
limit: OUTPUT_LIMIT
}).each_page do |log_event|
print log_event
log_message = ''
log_event['events'].each do |e|
date = Time.at(e['timestamp'][10]).since(9.hour)
log_message = log_message + '\n' + str(date) + ' : ' + e['message']
end
title = 'ラムダでエラー発生:' + log_group['logGroupName']
sns_message = message['AlarmDescription'] + '\n' + log_message
print sns_message
sns = Aws::Sns::Client.new(
region: 'ap-northeast-1'
)
sns.publish({
TopicArn: TOPIC_ARN,
Message: sns_message,
Subject: title
})
end
end
end
rescue
puts '何か問題が発生しました。'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment