I’d like to eliminate the common and error prone log prefix stuff we currently do.
Somewhat hardcoded:
$log.info("MIQ(Test##{__method__})...)
Or completely hardcoded:
$log.info("MIQ(Test#imethod)...)
I’d like to do just this in my code:
class Test
include LogPrefixMixin
def imethod
puts("#{log_prefix}...something")
end
def self.cmethod
puts("#{log_prefix}...something else")
end
end
This appears to work although I didn’t really test that much:
require 'active_support/concern'
module LogPrefixMixin
extend ActiveSupport::Concern
LOG_PREFIX_CLASS_SEPARATOR = '.'
LOG_PREFIX_INSTANCE_SEPARATOR = '#'
def log_prefix
self.class.format_log_prefix(LOG_PREFIX_INSTANCE_SEPARATOR)
end
module ClassMethods
def log_prefix
format_log_prefix(LOG_PREFIX_CLASS_SEPARATOR)
end
# Note: ruby 2.0 has caller_locations which is much faster
def _calling_method
caller[2][/`([^']*)'/, 1]
end
def format_log_prefix(seperator)
"MIQ(#{name}#{seperator}#{_calling_method})"
end
end
end
Output:
[1] pry(main)> require './log_prefix_mixin'
=> true
[2] pry(main)> Test.cmethod
MIQ(Test.cmethod)...something else
=> nil
[3] pry(main)> Test.new.imethod
MIQ(Test#imethod)...something
=> nil
Thoughts?