-
-
Save matsubo/0a365df297714decb68c97ea17abecfe to your computer and use it in GitHub Desktop.
Ruby AWS cloudwatch put log event example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
gem 'aws-sdk-cloudwatchlogs' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment