Sha256: 36dcc0bdd63c57acef936eeb79cf0245294ca33e0e00e816ec52009b44a1fb26

Contents?: true

Size: 1.39 KB

Versions: 3

Compression:

Stored size: 1.39 KB

Contents

# frozen_string_literal: true

require "logger"
require "stringio"
require "json"

require "memolog/version"
require "memolog/config"
require "memolog/init"
require "memolog/logger_extension"
require "memolog/rails_middleware"
require "memolog/sentry_extension"
require "memolog/sidekiq_middleware"

module Memolog
  extend self

  attr_accessor :config

  @config = Memolog::Config.new

  def configure
    yield(config) if block_given?
  end

  def init_middlewares!
    Memolog::Init.init_middlewares!
  end

  def extend_logger(other_logger)
    other_logger.extend(Memolog::LoggerExtension)
  end

  def run
    logdevs.push(StringIO.new)
    logger.instance_variable_set(:@logdev, logdevs.last)

    yield
  ensure
    logdevs.pop unless config.debug
  end

  def log(*args, &block)
    logger.log(*args, &block)
  end

  def dump(parse_json: false)
    return if logdevs.empty?

    beginning = logdevs.last.string.length - config.log_size_limit
    beginning = 0 if beginning.negative?

    dump = logdevs.last.string.slice(beginning, config.log_size_limit).presence

    dump && parse_json ? JSON.parse(dump) : dump
  rescue JSON::ParserError
    dump
  end

  private

  def logger
    storage[:memolog_logger] ||= Logger.new(nil, formatter: config.formatter)
  end

  def logdevs
    storage[:memolog_logdevs] ||= []
  end

  def storage
    config.isolation_level == :fiber ? Fiber : Thread.current
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
memolog-0.5.4 lib/memolog.rb
memolog-0.5.3 lib/memolog.rb
memolog-0.5.2 lib/memolog.rb