Class: Schedule::Logger
- Inherits:
-
Object
- Object
- Schedule::Logger
- Defined in:
- lib/schedule/logger.rb
Constant Summary collapse
- LINE_SEPERATOR =
CRLF, LF or CR
/\r\n|\n|\r/
Instance Attribute Summary collapse
-
#buffer ⇒ Object
readonly
Returns the value of attribute buffer.
Instance Method Summary collapse
- #close ⇒ Object
-
#initialize(device, prefix) ⇒ Logger
constructor
A new instance of Logger.
- #log(msg) ⇒ Object
Constructor Details
#initialize(device, prefix) ⇒ Logger
Returns a new instance of Logger.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/schedule/logger.rb', line 10 def initialize(device, prefix) if device == STDOUT @device = device elsif device.is_a?(String) @device = File.open(device, File::WRONLY | File::APPEND | File::CREAT) @device.sync = true else raise ArgumentError, "Log device must be a file path or STDOUT" end @formatter = Proc.new { |line, | "#{.strftime("%Y-%m-%d %H:%M:%S")} [#{@prefix}] #{line}" } @buffer = StringIO.new @prefix = prefix @semaphore = Mutex.new end |
Instance Attribute Details
#buffer ⇒ Object (readonly)
Returns the value of attribute buffer.
8 9 10 |
# File 'lib/schedule/logger.rb', line 8 def buffer @buffer end |
Instance Method Details
#close ⇒ Object
46 47 48 |
# File 'lib/schedule/logger.rb', line 46 def close @device.close end |
#log(msg) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/schedule/logger.rb', line 26 def log(msg) = Time.now # split into lines, preserving whitespace lines = msg.split(LINE_SEPERATOR) msg.scan(LINE_SEPERATOR).size.times { lines << "\n" } if lines.empty? unless lines.empty? @semaphore.synchronize do @device.flock(File::LOCK_EX) if device_is_file? begin @device.write(lines.map { |line| @formatter.call(line, ) }.join("\n") + "\n")# @buffer.write(lines.join("\n") + "\n") ensure @device.flock(File::LOCK_UN) if device_is_file? end end end end |