lib/syslogger.rb in syslogger-1.6.0 vs lib/syslogger.rb in syslogger-1.6.1

- old
+ new

@@ -2,11 +2,11 @@ require 'logger' require 'thread' class Syslogger - VERSION = "1.6.0" + VERSION = "1.6.1" attr_reader :level, :ident, :options, :facility, :max_octets attr_accessor :formatter MAPPING = { @@ -45,11 +45,13 @@ @ident = ident @options = options || (Syslog::LOG_PID | Syslog::LOG_CONS) @facility = facility @level = Logger::INFO @mutex = Mutex.new - @formatter = Logger::Formatter.new + @formatter = proc do |severity, datetime, progname, msg| + msg + end end %w{debug info warn error fatal unknown}.each do |logger_method| # Accepting *args as message could be nil. # Default params not supported in ruby 1.8.7 @@ -90,23 +92,24 @@ @mutex.synchronize do Syslog.open(progname, @options, @facility) do |s| s.mask = Syslog::LOG_UPTO(MAPPING[@level]) communication = clean(message || block && block.call) + formatted_communication = formatter.call([severity], Time.now, progname, communication) if self.max_octets - buffer = "" - communication.bytes do |byte| + buffer = "#{tags_text}" + formatted_communication.bytes do |byte| buffer.concat(byte) # if the last byte we added is potentially part of an escape, we'll go ahead and add another byte if buffer.bytesize >= self.max_octets && !['%'.ord,'\\'.ord].include?(byte) s.log(MAPPING[severity],buffer) buffer = "" end end s.log(MAPPING[severity],buffer) unless buffer.empty? else - s.log(MAPPING[severity],communication) + s.log(MAPPING[severity],"#{tags_text}#{formatted_communication}") end end end end @@ -130,17 +133,52 @@ # Sets the ident string passed along to Syslog def ident=(ident) @ident = ident end + # Tagging code borrowed from ActiveSupport gem + def tagged(*tags) + new_tags = push_tags(*tags) + yield self + ensure + pop_tags(new_tags.size) + end + + def push_tags(*tags) + tags.flatten.reject{ |i| i.respond_to?(:empty?) ? i.empty? : !i }.tap do |new_tags| + current_tags.concat new_tags + end + end + + def pop_tags(size = 1) + current_tags.pop size + end + + def clear_tags! + current_tags.clear + end + protected # Borrowed from SyslogLogger. def clean(message) message = message.to_s.dup message.strip! # remove whitespace message.gsub!(/\n/, '\\n') # escape newlines message.gsub!(/%/, '%%') # syslog(3) freaks on % (printf) message.gsub!(/\e\[[^m]*m/, '') # remove useless ansi color codes message + end + + private + + def tags_text + tags = current_tags + if tags.any? + tags.collect { |tag| "[#{tag}] " }.join + end + end + + def current_tags + Thread.current[:syslogger_tagged_logging_tags] ||= [] end end