Class: LogMonitor::LogMonitorService

Inherits:
Object
  • Object
show all
Defined in:
lib/rails-tail-log-monitor.rb

Constant Summary collapse

ANSI_TO_HTML =
{
  '30' => 'black',
  '31' => 'red',
  '32' => 'green',
  '33' => 'yellow',
  '34' => 'blue',
  '35' => 'magenta',
  '36' => 'cyan',
  '37' => 'white',
  '90' => 'darkgrey',
  '91' => 'lightred',
  '92' => 'lightgreen',
  '93' => 'lightyellow',
  '94' => 'lightblue',
  '95' => 'lightmagenta',
  '96' => 'lightcyan',
  '97' => 'lightgrey'
}.freeze

Class Method Summary collapse

Class Method Details

.ansi_to_html(log) ⇒ Object



112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/rails-tail-log-monitor.rb', line 112

def self.ansi_to_html(log)
  return '<br>' if log.blank?

  html_text = log.dup
  html_text = html_text.gsub('<', '&lt;').gsub('>', '&gt;')
  ANSI_TO_HTML.each_key do |code|
    html_text.gsub!(/\e\[#{code}m/, "<span style='color: #{ANSI_TO_HTML[code]};'>")
  end
  html_text.gsub!(/\e\[0m/, '</span>')
  html_text.gsub!(/\e\[1m/, "<span style='font-weight: bold;'>")
  html_text
end

.monitor_logObject



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
# File 'lib/rails-tail-log-monitor.rb', line 82

def self.monitor_log
  log_file = Rails.root.join('log', "#{Rails.env}.log")
  last_position = File.size(log_file)

  begin
    loop do
      sleep 0.3
      if Time.zone.now.to_i - $monitoring_keep_alive > LogMonitor.configuration.keep_alive_time
        stop_monitoring
        break
      else
        new_log_entries = File.open(log_file, 'r') do |file|
          file.seek(last_position)
          file.read
        end.split("\n", -1)
        if new_log_entries.present?
          new_log_entries = new_log_entries[0..-2] if new_log_entries.last.empty?
          ActionCable.server.broadcast(
            'log_channel', { log_entries: new_log_entries.map { |log| ansi_to_html(log) } }
          )
        end

        last_position = File.size(log_file)
      end
    end
  rescue StandardError => e
    Rails.logger.error "Error in LogMonitorService: #{e.message}"
  end
end

.start_monitoringObject



71
72
73
74
# File 'lib/rails-tail-log-monitor.rb', line 71

def self.start_monitoring
  $monitoring_keep_alive = Time.zone.now.to_i
  $monitoring_thread ||= Thread.new { monitor_log }
end

.stop_monitoringObject



76
77
78
79
80
# File 'lib/rails-tail-log-monitor.rb', line 76

def self.stop_monitoring
  $monitoring_thread&.kill
  $monitoring_thread&.join
  $monitoring_thread = nil
end