Class: Trinidad::Logging::FileHandler

Inherits:
Java::OrgApacheJuli::FileHandler
  • Object
show all
Defined in:
lib/trinidad/logging.rb

Overview

we’d achieve logging to a production.log file while rotating it (daily)

Instance Method Summary collapse

Constructor Details

#initialize(directory, prefix, suffix) ⇒ FileHandler

Returns a new instance of FileHandler.



134
135
136
137
# File 'lib/trinidad/logging.rb', line 134

def initialize(directory, prefix, suffix)
  super(directory, prefix, suffix)
  self._date = '' # to openWriter on first #publish(record)
end

Instance Method Details

#closeObject



156
157
158
159
160
# File 'lib/trinidad/logging.rb', line 156

def close
  @_close = true
  super
  @_close = nil
end

#closeWriterObject



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/trinidad/logging.rb', line 162

def closeWriter
  date = _date
  super # sets `date = null`
  # the additional trick here is to rotate the closed file
  synchronized do
    # we're normally in the lock here (from #publish) 
    # thus we do not perform any more synchronization
    dir = java.io.File.new(directory).getAbsoluteFile
    log = java.io.File.new(dir, prefix + "" + suffix)
    if log.exists
      if ! date || date.empty?
        date = log.lastModified
        # we abuse Timestamp to get a date formatted !
        # just like super does internally (just in case)
        date = java.sql.Timestamp.new(date).toString[0, 10]
      end
      today = java.lang.System.currentTimeMillis
      today = java.sql.Timestamp.new(today).toString[0, 10]
      return if date == today # no need to rotate just yet
      to_file = java.io.File.new(dir, prefix + date + suffix)
      if to_file.exists
        file = java.io.RandomAccessFile.new(to_file, 'rw')
        file.seek(file.length)
        log_channel = java.io.FileInputStream.new(log).getChannel
        log_channel.transferTo(0, log_channel.size, file.getChannel)
        file.close
        log_channel.close
        log.delete
      else
        log.renameTo(to_file)
      end
    end
  end if rotatable && ! @_close
end

#openWriterObject



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/trinidad/logging.rb', line 139

def openWriter
  # NOTE: following code is heavily based on super's internals !
  synchronized do
    # we're normally in the lock here (from #publish) 
    # thus we do not perform any more synchronization
    prev_rotatable = self.rotatable
    begin
      self.rotatable = false
      # thus current file name will be always {prefix}{suffix} :
      # due super's `prefix + (rotatable ? _date : "") + suffix`
      super
    ensure
      self.rotatable = prev_rotatable
    end
  end
end