Class: UpdateRepo::Logger

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/update_repo/logger.rb

Overview

Class : Logger. This class encapsulates printing to screen and logging to file if requried.

Instance Method Summary collapse

Methods included from Helpers

#trunc_dir

Constructor Details

#initialize(enabled, timestamp) ⇒ void

Constructor for the Logger class.

Examples:

log = Logger.new(true, false)

Parameters:

  • enabled (boolean)

    True if we log to file

  • timestamp (boolean)

    True if we timestamp the filename



16
17
18
19
20
21
22
23
24
25
# File 'lib/update_repo/logger.rb', line 16

def initialize(enabled, timestamp)
  @settings = { enabled: enabled, timestamp: timestamp }
  # don't prepare a logfile unless it's been requested.
  return unless @settings[:enabled]
  # generate a filename depending on 'timestamp' setting.
  filename = generate_filename
  # open the logfile and set sync mode.
  @logfile = File.open(filename, 'w')
  @logfile.sync = true
end

Instance Method Details

#closevoid

This method returns an undefined value.

close the logfile, if it exists

Parameters:

  • (none)


53
54
55
# File 'lib/update_repo/logger.rb', line 53

def close
  @logfile.close if @logfile
end

#generate_filenamestring

generate a filename for the log, with or without a timestamp

Parameters:

  • (none)

Returns:

  • (string)

    Filename for the logfile.



30
31
32
33
34
35
36
# File 'lib/update_repo/logger.rb', line 30

def generate_filename
  if @settings[:timestamp]
    'updaterepo-' + Time.new.strftime('%y%m%d-%H%M%S') + '.log'
  else
    'updaterepo.log'
  end
end

#output(*string) ⇒ void

This method returns an undefined value.

this function will simply pass the given string to ‘print’, and also log to file if that is specified.

Parameters:

  • string (array)

    Array of strings for print formatting



42
43
44
45
46
47
48
# File 'lib/update_repo/logger.rb', line 42

def output(*string)
  # log to screen regardless
  print(*string)
  # log to file if that has been enabled
  return unless @settings[:enabled]
  @logfile.write(string.join('').gsub(/\e\[(\d+)(;\d+)*m/, ''))
end