Skip to content

Instantly share code, notes, and snippets.

@matsubo
Forked from run26kimo/Gemfile
Last active Mar 12, 2021
Embed
What would you like to do?
Ruby AWS cloudwatch put log event example
environment = 'test'
project_id = rand(1...10000)
group_name = "bulk-mail"
stream_name = "#{environment}-#{project_id}"
region = 'ap-northeast-1'
client = Aws::CloudWatchLogs::Client.new(region: region)
result = client.create_log_stream({
log_group_name: group_name,
log_stream_name: stream_name
})
5.times do
message = {
user_id: rand(1...10000)
}
begin
event = {
log_group_name: group_name,
log_stream_name: stream_name,
log_events: [{
timestamp: (Time.now.utc.to_f.round(3)*1000).to_i,
message: message.to_json
}]
}
if token = @sequence_token
event[:sequence_token] = token
end
response = client.put_log_events(event)
unless response.rejected_log_events_info.nil?
raise CloudWatchLogger::LogEventRejected
end
@sequence_token = response.next_sequence_token
rescue Aws::CloudWatchLogs::Errors::ResourceNotFoundException => err
resp = client.create_log_stream({
log_group_name: group_name,
log_stream_name: stream_name,
})
retry
rescue Aws::CloudWatchLogs::Errors::InvalidSequenceTokenException => err
@sequence_token = err.message.split(' ').last
retry
end
end
gem 'aws-sdk-cloudwatchlogs'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment