Class: Cosmos::MessageLog

Inherits:
Object show all
Defined in:
lib/cosmos/utilities/message_log.rb

Overview

Handles writing message logs to a file

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tool_name, log_dir = nil) ⇒ MessageLog

Returns a new instance of MessageLog.

Parameters:

  • tool_name (String)

    The name of the tool creating the message log. This will be inserted into the message log file name to help identify it.

  • log_dir (String) (defaults to: nil)

    The filesystem path to store the message log file.



28
29
30
31
32
33
34
35
36
# File 'lib/cosmos/utilities/message_log.rb', line 28

def initialize(tool_name, log_dir = nil)
  @tool_name = tool_name
  @log_dir = ConfigParser.handle_nil(log_dir)
  @log_dir = System.paths['LOGS'] unless @log_dir
  @filename = ''
  @file = nil
  @start_time = nil
  @mutex = Mutex.new
end

Instance Attribute Details

#filenameString (readonly)

Returns The name of the message log file. Empty string until the write or start methods are called at which point it is set to the filename. Retains the last filename even after stop is called.

Returns:

  • (String)

    The name of the message log file. Empty string until the write or start methods are called at which point it is set to the filename. Retains the last filename even after stop is called.



23
24
25
# File 'lib/cosmos/utilities/message_log.rb', line 23

def filename
  @filename
end

Instance Method Details

#start(take_mutex = true) ⇒ Object

Creates a new message log and sets the filename



65
66
67
68
69
70
71
72
73
74
75
# File 'lib/cosmos/utilities/message_log.rb', line 65

def start(take_mutex = true)
  @mutex.lock if take_mutex
  # Prevent starting files too fast
  sleep(0.1) until !File.exist?(File.join(@log_dir, File.build_timestamped_filename([@tool_name, 'messages'])))
  stop(false)
  Cosmos.set_working_dir do
    @filename = File.join(@log_dir, File.build_timestamped_filename([@tool_name, 'messages']))
    @file = File.open(@filename, 'a')
  end
  @mutex.unlock if take_mutex
end

#stop(take_mutex = true) ⇒ Object

Closes the message log and marks it read only



53
54
55
56
57
58
59
60
61
62
# File 'lib/cosmos/utilities/message_log.rb', line 53

def stop(take_mutex = true)
  @mutex.lock if take_mutex
  if @file and not @file.closed?
    @file.close
    Cosmos.set_working_dir do
      File.chmod(0444, @filename)
    end
  end
  @mutex.unlock if take_mutex
end

#write(message) ⇒ Object

Ensures the log file is opened and ready to write. It then writes the message to the log and flushes it to force the write.

Parameters:

  • message (String)

    Message to write to the log



42
43
44
45
46
47
48
49
50
# File 'lib/cosmos/utilities/message_log.rb', line 42

def write(message)
  @mutex.synchronize do
    if @file.nil? or @file.closed? or (not File.exist?(@filename))
      start(false)
    end

    @file.write(message)
  end
end