semantic_logger icon indicating copy to clipboard operation
semantic_logger copied to clipboard

Suggestion: add an option to disable lazy initialization in Loggable's logger methods

Open keithrbennett opened this issue 3 years ago • 0 comments

Environment

  • Ruby version 2.7.6
  • Semantic Logger version 4.11.0.

The SemanticLogger::Loggable module provides an instance logger method that lazily initializes a @semantic_logger instance variable. If the instance is frozen the first time logger is called, then an error like this is raised:

...semantic_logger-4.11.0/lib/semantic_logger/loggable.rb:55:in `logger': 
can't modify frozen C: #<C:0x00000001100935b0> (FrozenError)

One solution to this is to call logger somewhere in your constructor. That way the instance variable will be initialized before the object can be frozen. The following script can be used to illustrate this:

#!/usr/bin/env ruby

require 'semantic_logger'

class C
  include SemanticLogger::Loggable

  def initialize
    # Enabling the `logger` line below will cause the logger instance variable to be initialized
    # here in the constructor, before `freeze` can be called on the object.
    # logger  
  end

  def foo
    logger.error 'error'
  end
end

c = C.new
c.freeze
c.foo

# If the logger has not been initialized before freezing, the following error will be raised:
#   semantic_logger-4.11.0/lib/semantic_logger/loggable.rb:55:in `logger': 
#   can't modify frozen C: #<C:0x00000001100935b0> (FrozenError)

It would be even nicer if there were an option to turn off lazy initialization, e.g.:

SemanticLogger.lazy_initialization_enabled = false

This would eliminate the need for the workaround in the constructor. This workaround would need to be in any class whose instances could potentially be frozen, which really means any class at all. As freezing objects becomes more prevalent, this will become more of an issue.

Alternatively, the nonlazy approach could be used by default, or possibly even be the only option.

keithrbennett avatar Sep 14 '22 19:09 keithrbennett