Class: VCAP::Logging::Sink::FileSink

Inherits:
BaseSink
  • Object
show all
Defined in:
lib/vcap/logging/sink/file_sink.rb

Overview

A sink for writing to a file. Buffering is supported, but disabled by default.

Defined Under Namespace

Classes: MessageBuffer

Instance Attribute Summary collapse

Attributes inherited from BaseSink

#autoflush, #formatter, #opened

Instance Method Summary collapse

Methods inherited from BaseSink

#add_record

Constructor Details

#initialize(filename, formatter = nil, opts = {}) ⇒ FileSink

Returns a new instance of FileSink.

Parameters:

  • filename

    String Pretty obvious…

  • formatter (defaults to: nil)

    BaseFormatter Formatter to use when generating log messages

  • opts (defaults to: {})

    Hash :buffer_size => Size (in bytes) to buffer in memory before flushing to disk



44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/vcap/logging/sink/file_sink.rb', line 44

def initialize(filename, formatter=nil, opts={})
  super(formatter)

  @filename = filename
  @file     = nil
  if opts[:buffer_size] && (Integer(opts[:buffer_size]) > 0)
    @buffer = MessageBuffer.new(opts[:buffer_size])
  else
    @buffer = nil
  end
  open()
end

Instance Attribute Details

#filenameObject (readonly)

Returns the value of attribute filename.



6
7
8
# File 'lib/vcap/logging/sink/file_sink.rb', line 6

def filename
  @filename
end

Instance Method Details

#closeObject



70
71
72
73
74
75
76
77
78
79
# File 'lib/vcap/logging/sink/file_sink.rb', line 70

def close
  @mutex.synchronize do
    if @opened
      perform_write(@buffer.compact) if @buffer && !@buffer.empty?
      @file.close
      @file = nil
      @opened = false
    end
  end
end

#flushObject



81
82
83
84
85
# File 'lib/vcap/logging/sink/file_sink.rb', line 81

def flush
  @mutex.synchronize do
    perform_write(@buffer.compact) if @buffer && !@buffer.empty?
  end
end

#openObject

Missing Python’s decorators pretty badly here. Even guards would be better than the existing solution. Alas, ruby has no real destructors.



60
61
62
63
64
65
66
67
68
# File 'lib/vcap/logging/sink/file_sink.rb', line 60

def open
  @mutex.synchronize do
    if !@opened
      @file = File.new(@filename, 'a+')
      @file.sync = true
      @opened = true
    end
  end
end