Class: Cosmos::MessageLog
Overview
Handles writing message logs to a file
Instance Attribute Summary collapse
-
#filename ⇒ String
readonly
The name of the message log file.
Instance Method Summary collapse
-
#initialize(tool_name, log_dir, scope:) ⇒ MessageLog
constructor
A new instance of MessageLog.
-
#start(take_mutex = true) ⇒ Object
Creates a new message log and sets the filename.
-
#stop(take_mutex = true, s3_object_metadata: {}) ⇒ Object
Closes the message log and marks it read only.
-
#write(message, flush = false) ⇒ Object
Ensures the log file is opened and ready to write.
Constructor Details
#initialize(tool_name, log_dir, scope:) ⇒ MessageLog
Returns a new instance of MessageLog.
36 37 38 39 40 41 42 43 44 |
# File 'lib/cosmos/utilities/message_log.rb', line 36 def initialize(tool_name, log_dir, scope:) @remote_log_directory = "#{scope}/tool_logs/#{tool_name}/" @tool_name = tool_name @log_dir = log_dir @filename = '' @file = nil @start_day = nil @mutex = Mutex.new end |
Instance Attribute Details
#filename ⇒ String (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.
31 32 33 |
# File 'lib/cosmos/utilities/message_log.rb', line 31 def filename @filename end |
Instance Method Details
#start(take_mutex = true) ⇒ Object
Creates a new message log and sets the filename
79 80 81 82 83 84 85 86 87 88 89 |
# File 'lib/cosmos/utilities/message_log.rb', line 79 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.([@tool_name, 'messages']))) stop(false) timed_filename = File.([@tool_name, 'messages']) @start_day = timed_filename[0..9].gsub("_", "") # YYYYMMDD @filename = File.join(@log_dir, timed_filename) @file = File.open(@filename, 'a') @mutex.unlock if take_mutex end |
#stop(take_mutex = true, s3_object_metadata: {}) ⇒ Object
Closes the message log and marks it read only
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/cosmos/utilities/message_log.rb', line 62 def stop(take_mutex = true, s3_object_metadata: {}) @mutex.lock if take_mutex if @file and not @file.closed? @file.close File.chmod(0444, @filename) s3_key = File.join(@remote_log_directory, @start_day, File.basename(@filename)) begin thread = S3Utilities.move_log_file_to_s3(@filename, s3_key, metadata: ) thread.join rescue StandardError => e Logger.error e.formatted end end @mutex.unlock if take_mutex end |
#write(message, flush = false) ⇒ 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.
50 51 52 53 54 55 56 57 58 59 |
# File 'lib/cosmos/utilities/message_log.rb', line 50 def write(, flush = false) @mutex.synchronize do if @file.nil? or @file.closed? or (not File.exist?(@filename)) start(false) end @file.write() @file.flush if flush end end |