Class: Bwrap::Output::Log

Inherits:
Object
  • Object
show all
Defined in:
lib/bwrap/output/log.rb

Overview

Note:

One should require “bwrap/output” instead of this file directly, even if using only methods from this class.

This is because Bwrap::Output module would be missing, or there could be a circular dependency, which is always bad, even if Ruby would break it for you.

Logging methods.

Constant Summary collapse

@@log_file =
nil

Class Method Summary collapse

Class Method Details

.close_log_fileObject

Closes an open log file.



35
36
37
38
# File 'lib/bwrap/output/log.rb', line 35

def self.close_log_file
  @@log_file&.close
  @@log_file = nil
end

.log_fileObject

Get handle of opened log file.



14
15
16
# File 'lib/bwrap/output/log.rb', line 14

def self.log_file
  @@log_file
end

.log_to_file(log_path) ⇒ Object

Starts logging to given file.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/bwrap/output/log.rb', line 41

def self.log_to_file log_path
  unless File.writable? log_path
    warn "Given log file #{log_path} is not writable by current user."
    return
  end
  log_file = File.open log_path, "w"

  # In default mode, log messages disappears as Ruby’s own buffer gets full.
  # This makes only OS buffer being used.
  log_file.sync = false

  @@log_file = log_file

  at_exit do
    Bwrap::Output::Log.close_log_file
  end
end

.puts_to_log(str) ⇒ Object

Writes given string to log.



27
28
29
30
31
32
# File 'lib/bwrap/output/log.rb', line 27

def self.puts_to_log str
  # Guard against invalid input.
  return unless str.respond_to? :force_encoding

  @@log_file&.puts str.dup.force_encoding("UTF-8")
end

.write_to_log(str) ⇒ Object

Writes given string to log.



19
20
21
22
23
24
# File 'lib/bwrap/output/log.rb', line 19

def self.write_to_log str
  # Guard against invalid input.
  return unless str.respond_to? :force_encoding

  @@log_file&.write str.dup.force_encoding("UTF-8")
end