Skip to content

Instantly share code, notes, and snippets.

@lloeki
Created January 21, 2022 18:00
Show Gist options
  • Save lloeki/8590e07438f91ed83fe9e89232d3850a to your computer and use it in GitHub Desktop.
Save lloeki/8590e07438f91ed83fe9e89232d3850a to your computer and use it in GitHub Desktop.
Loggable Ruby module
require 'logger'
module Core
def self.logger
@logger ||= Loggable::Logger.new(STDOUT, progname: name, level: Logger::DEBUG)
end
end
module Loggable
class Logger < ::Logger
# TODO: add filters based on progname
end
def self.included(klass)
klass.extend(ClassMethods)
end
module ClassMethods
def logger
@logger ||= Core.logger.dup.tap { |l| l.progname = name }
end
attr_writer :logger
end
def logger
@logger || singleton_class.logger
end
attr_writer :logger
end
module Demo
module Foo
include Loggable
def hello
Foo.logger.warn { 'foo meth' }
end
def self.hello
logger.warn { 'foo mod' }
end
module Bar
def hello
Foo.logger.warn { 'bar' }
end
end
end
module Baz
include Loggable
def hello
Baz.logger.warn { 'baz' }
end
end
class A
include Foo
end
class B
include Foo::Bar
end
class C
include Baz
end
class D
include Loggable
def hello
logger.warn { 'qux meth' }
end
def self.hello
logger.warn { 'qux class' }
end
end
end
Demo::Foo.hello
Demo::A.new.hello
Demo::B.new.hello
Demo::C.new.hello
Demo::D.hello
Demo::D.new.hello
# W, [2022-01-21T18:59:17.137446 #735301] WARN -- Demo::Foo: foo mod
# W, [2022-01-21T18:59:17.137500 #735301] WARN -- Demo::Foo: foo meth
# W, [2022-01-21T18:59:17.137543 #735301] WARN -- Demo::Foo: bar
# W, [2022-01-21T18:59:17.137553 #735301] WARN -- Demo::Baz: baz
# W, [2022-01-21T18:59:17.137560 #735301] WARN -- Demo::D: qux class
# W, [2022-01-21T18:59:17.137569 #735301] WARN -- : qux meth
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment