Sha256: 7d2f47b8f66b68f98d496398fe5474cc487329f84f7e3e112134d230024fd1a3

Contents?: true

Size: 1.7 KB

Versions: 4

Compression:

Stored size: 1.7 KB

Contents

require 'monitor'

class StrftimeLogger
  class Adapter
    class File

      class LogFileMutex
        include MonitorMixin
      end

      def initialize(level, path)
        @level = level
        @path = path
        @timestamp_path = Time.now.strftime(path)
        @mutex = LogFileMutex.new
        @log = open_logfile(@timestamp_path)
      end

      def write(msg)
        begin
          @mutex.synchronize do
            if @log.nil? || !same_path?
              begin
                @timestamp_path = Time.now.strftime(@path)
                @log.close rescue nil
                @log = create_logfile(@timestamp_path)
              rescue
                warn("log shifting failed. #{$!}")
              end
            end

            begin
              @log.write msg
            rescue
              warn("log writing failed. #{$!}")
            end
          end
        rescue Exception => ignored
          warn("log writing failed. #{ignored}")
        end
      end

      def close
        if !@log.nil? && !@log.closed?
          @log.close
        end
      end

      private

      # return nil if file not found
      def open_logfile(filename)
        begin
          f = ::File.open filename, (::File::WRONLY | ::File::APPEND)
          f.sync = true
        rescue Errno::ENOENT
          return nil
        end
        f
      end

      def create_logfile(filename)
        begin
          f = ::File.open filename, (::File::WRONLY | ::File::APPEND | ::File::CREAT | ::File::EXCL)
          f.sync = true
        rescue Errno::EEXIST
          f = open_logfile(filename)
        end
        f
      end

      def same_path?
        @timestamp_path == Time.now.strftime(@path)
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
strftime_logger-0.0.4 lib/strftime_logger/adapter/file.rb
strftime_logger-0.0.3 lib/strftime_logger/adapter/file.rb
strftime_logger-0.0.2 lib/strftime_logger/adapter/file.rb
strftime_logger-0.0.1 lib/strftime_logger/adapter/file.rb