Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby AWS cloudwatch put log event example
# AWS cloudwatch log document
# https://docs.aws.amazon.com/sdkforruby/api/Aws/CloudWatchLogs/Client.html#put_log_events-instance_method
group_name = "group_name" # cloudwatch log group name
stream_name = "stream_name"# cloudwatch log stream name
region = 'ap-southeast-1' #aws region
message = {
url: "https://www.google.tw",
time: "#{Time.now.getutc.to_i}"
}
client = Aws::CloudWatchLogs::Client.new(region: region)
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
gem 'aws-sdk-cloudwatchlogs'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment