Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
uoy-faculty-sinatra-aws / lib / sinatra / faculty / aws_alternate_logs.rb
Size: Mime:
# frozen_string_literal: true

require 'aws-sdk-cloudwatchlogs'

# Top-level module documentation comment goes here...
module Sinatra
  module Faculty
    # Create a Logger-like interface to allow logs to be written to the specified log group and log stream.
    # The lambda requires logs:DescribeLogStreams on the log group
    class AwsAlternateLogs
      def initialize(group_name, stream_name)
        @group_name = group_name
        @stream_name = stream_name
        @client = Aws::CloudWatchLogs::Client.new
        @client.create_log_stream({ log_group_name: @group_name, log_stream_name: @stream_name }) unless stream_exists?
      end

      def write(msg)
        @client.put_log_events({ log_group_name: @group_name,
                                 log_stream_name: @stream_name,
                                 log_events: [{ timestamp: (Time.now.to_f * 1000).round,
                                                message: msg }],
                                 sequence_token: sequence_token })
      end

      private

      def stream_exists?
        !described_stream.log_streams.empty?
      end

      def sequence_token
        described_stream.log_streams.first&.upload_sequence_token
      end

      def described_stream
        @client.describe_log_streams({ log_group_name: @group_name,
                                       log_stream_name_prefix: @stream_name,
                                       order_by: 'LogStreamName',
                                       descending: false,
                                       limit: 1 })
      end
    end
  end
end