Class: Logging::Appenders::RollingFile

Inherits:
IO
  • Object
show all
Defined in:
lib/ubsafe/extensions/ubsafe_logging_extensions.rb

Instance Method Summary collapse

Constructor Details

#initialize(name, opts = {}) ⇒ RollingFile

Returns a new instance of RollingFile.

Raises:

  • (ArgumentError)


49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/ubsafe/extensions/ubsafe_logging_extensions.rb', line 49

def initialize( name, opts = {} )
  # raise an error if a filename was not given
  @fn = opts.getopt(:filename, name)
  raise ArgumentError, 'no filename was given' if @fn.nil?
  ::Logging::Appenders::File.assert_valid_logfile(@fn)

  # grab the information we need to properly roll files
  ext = ::File.extname(@fn)
  bn = ::File.join(::File.dirname(@fn), ::File.basename(@fn, ext))
  @rgxp = %r/\.(\d+)#{Regexp.escape(ext)}\z/
  @glob = "#{bn}.*#{ext}"
  @logname_fmt = "#{bn}.%d#{ext}"

  # grab our options
  @keep = opts.getopt(:keep, :as => Integer)
  @size = opts.getopt(:size, :as => Integer)

  @lockfile = if opts.getopt(:safe, false) and !::Logging::WIN32
    ::Lockfile.new(
        @fn + '.lck',
        :retries => 1,
        :timeout => 2
    )
  end

  code = 'def sufficiently_aged?() false end'
  @age_fn = @fn + '.age'

  case @age = opts.getopt(:age)
  when 'daily'
    FileUtils.touch(@age_fn) unless test(?f, @age_fn)
    code = <<-CODE
    def sufficiently_aged?
      now = Time.now.utc
      start = ::File.mtime(@age_fn).utc
      if (now.day != start.day) or (now - start) > 86400
        return true
      end
      false
    end
    CODE
  when 'weekly'
    FileUtils.touch(@age_fn) unless test(?f, @age_fn)
    code = <<-CODE
    def sufficiently_aged?
      if (Time.now.utc - ::File.mtime(@age_fn).utc) > 604800
        return true
      end
      false
    end
    CODE
  when 'monthly'
    FileUtils.touch(@age_fn) unless test(?f, @age_fn)
    code = <<-CODE
    def sufficiently_aged?
      now = Time.now.utc
      start = ::File.mtime(@age_fn).utc
      if (now.month != start.month) or (now - start) > 2678400
        return true
      end
      false
    end
    CODE
  when Integer, String
    @age = Integer(@age)
    FileUtils.touch(@age_fn) unless test(?f, @age_fn)
    code = <<-CODE
    def sufficiently_aged?
      if (Time.now.utc - ::File.mtime(@age_fn).utc) > @age
        return true
      end
      false
    end
    CODE
  end
  meta = class << self; self end
  meta.class_eval code, __FILE__, __LINE__

  # if the truncate flag was set to true, then roll 
  roll_now = opts.getopt(:truncate, false)
  roll_files if roll_now

  super(name, open_logfile, opts)
end