Skip to content

Commit

Permalink
This allows us to propagate the logger to child fibers/threads. (#59)
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix authored Apr 30, 2024
1 parent fcbe0e5 commit 8e39181
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
2 changes: 1 addition & 1 deletion console.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ Gem::Specification.new do |spec|
spec.required_ruby_version = ">= 3.0"

spec.add_dependency "fiber-annotation"
spec.add_dependency "fiber-local"
spec.add_dependency "fiber-storage"
spec.add_dependency "json"
end
12 changes: 7 additions & 5 deletions lib/console/logger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,10 @@
require_relative 'terminal/logger'
require_relative 'serialized/logger'

require 'fiber/local'
require 'fiber/storage'

module Console
class Logger < Filter[debug: 0, info: 1, warn: 2, error: 3, fatal: 4]
extend Fiber::Local

# Set the default log level based on `$DEBUG` and `$VERBOSE`.
# You can also specify CONSOLE_LEVEL=debug or CONSOLE_LEVEL=info in environment.
# https://mislav.net/2011/06/ruby-verbose-mode/ has more details about how it all fits together.
Expand Down Expand Up @@ -56,8 +54,12 @@ def self.default_logger(output = $stderr, env = ENV, **options)
return logger
end

def self.local
self.default_logger
def self.instance
Fiber[:console_logger] ||= self.default_logger
end

def self.instance=(logger)
Fiber[:console_logger] = logger
end

DEFAULT_LEVEL = 1
Expand Down
16 changes: 16 additions & 0 deletions test/console/logger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,22 @@

let(:message) {"Hello World"}

with '.instance' do
it "propagates to child thread" do
Fiber.new do
expect(Fiber[:console_logger]).to be_nil

logger = Console::Logger.instance

Fiber.new do
expect(Console::Logger.instance).to be_equal(logger)
end.resume
end.resume

expect(Fiber[:console_logger]).to be_nil
end
end

with '#with' do
let(:nested) {logger.with(name: "nested", level: :debug)}

Expand Down

0 comments on commit 8e39181

Please sign in to comment.