Skip to content

Instantly share code, notes, and snippets.

@suzumura-ss
Last active December 23, 2015 02:27
Show Gist options
  • Save suzumura-ss/c40308cec350b252e2cb to your computer and use it in GitHub Desktop.
Save suzumura-ss/c40308cec350b252e2cb to your computer and use it in GitHub Desktop.
put CloudWatchLogs with X_CLOUDWATCH_LOG header
=begin
require 'grape'
require 'uuid'
require 'ltsv'
class Hello < Grape::API
post 'teapot' do
status 201
id = UUID.generate
header XCloudwatchLogFilter::X_CLOUDWATCH_LOG, LTSV.dump({user_id:id, resource:'/teapot'})
body = request.body.read
{id:id}
end
end
use XCloudwatchLogFilter
run Hello
=end
require 'aws-sdk'
class XCloudwatchLogFilter
LOG_GROUP_NAME = 'example'
LOG_STREAM_NAME = 'api_calls'
X_CLOUDWATCH_LOG = 'x_cloudwatch_log'
@@client = nil
@@next_sequence_token = nil
def self.put_log_event(message)
@@client ||= Aws::CloudWatchLogs::Client.new(region:ENV['AWS_REGION'], http_proxy:ENV['HTTPS_PROXY']||ENV['HTTP_PROXY'])
param = {
log_group_name:LOG_GROUP_NAME,
log_stream_name:LOG_STREAM_NAME,
log_events:[{
timestamp:(Time.now.to_f*1000).to_i,
message:message
}]
}
param.merge!(sequence_token:@@next_sequence_token) if @@next_sequence_token
begin
res = @@client.put_log_events(param)
rescue Aws::CloudWatchLogs::Errors::InvalidSequenceTokenException=>e
seq = e.to_s.scan(/\d{48,}/)[0]
param.merge!(sequence_token:seq)
retry
end
p(log:res)
@@next_sequence_token = res.next_sequence_token
end
def initialize(app)
@app = app
end
def call(env)
res = @app.call(env)
apicall = res[1][X_CLOUDWATCH_LOG]
if apicall
XCloudwatchLogFilter.put_log_event(apicall)
res[1].delete(X_CLOUDWATCH_LOG)
end
res
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment