Sha256: 6ba41e35e2ca09fb907383d95958c3e506d1c47a44ebc7a2aef9c9c045343be3

Contents?: true

Size: 1.63 KB

Versions: 18

Compression:

Stored size: 1.63 KB

Contents

module Logical
  module Naf
    class LogFile
      LOG_MAX_SIZE = 50_000

      attr_reader :file_line_number,
                    :line_number,
                    :file,
                    :log_area,
                    :lines_cache

      def initialize(log_area)
        @file_line_number = @line_number = 1
        @file = nil
        @log_area = log_area
        @lines_cache = ''
      end

      def <<(message)
        log_line = JSON.pretty_generate({
          line_number: line_number,
          output_time: Time.zone.now.strftime("%Y-%m-%d %H:%M:%S.%L"),
          message: message
         })
        @lines_cache << log_line
        @line_number += 1
      end

      def write
        check_file_size
        output = lines_cache
        unless output.blank?
          file.write(output)
          @lines_cache = ''
          flush
        end
      end

      def flush
        file.flush
      end

      def open
        # Create the directory path if it doesn't exist
        FileUtils.mkdir_p(log_area)

        filename = Dir[log_area + "/#{file_line_number}_*"].first
        if filename.blank?
          @file = File.open(log_area + "/#{file_line_number}_#{Time.zone.now.strftime('%Y%m%d_%H%M%S')}.json", 'wb')
        else
          @file = File.open(filename, 'wb')
        end
      end

      def close
        @file.try(:close)
        @file = nil
      end

      def check_file_size
        if file.size > LOG_MAX_SIZE
          @file_line_number = line_number
          close
          @file = File.open(log_area + "/#{file_line_number}_#{Time.zone.now.strftime('%Y%m%d_%H%M%S')}.json", 'wb')
        end
      end
    end

  end
end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
naf-2.1.13 app/models/logical/naf/log_file.rb
naf-2.1.12 app/models/logical/naf/log_file.rb
naf-2.1.11 app/models/logical/naf/log_file.rb
naf-2.1.10 app/models/logical/naf/log_file.rb
naf-2.1.9 app/models/logical/naf/log_file.rb
naf-2.1.8 app/models/logical/naf/log_file.rb
naf-2.1.6 app/models/logical/naf/log_file.rb
naf-2.1.5 app/models/logical/naf/log_file.rb
naf-2.1.4 app/models/logical/naf/log_file.rb
naf-2.1.3 app/models/logical/naf/log_file.rb
naf-2.1.2 app/models/logical/naf/log_file.rb
naf-2.1.1 app/models/logical/naf/log_file.rb
naf-2.1.0 app/models/logical/naf/log_file.rb
naf-2.0.4 app/models/logical/naf/log_file.rb
naf-2.0.3 app/models/logical/naf/log_file.rb
naf-2.0.2 app/models/logical/naf/log_file.rb
naf-2.0.1 app/models/logical/naf/log_file.rb
naf-2.0.0 app/models/logical/naf/log_file.rb