Class: LogViewer::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/logviewer.rb

Constant Summary collapse

LOG_LEVELS =
{
  'trace' => 0,
  'debug' => 1,
  'info' => 2,
  'notice' => 3,
  'warning' => 4,
  'error' => 5,
  'critical' => 6
}

Instance Method Summary collapse

Constructor Details

#initialize(args = ARGV) ⇒ CLI

Returns a new instance of CLI.



19
20
21
22
23
# File 'lib/logviewer.rb', line 19

def initialize(args = ARGV)
  @args = args
  @min_level = 'debug'
  @input_file = nil
end

Instance Method Details

#extract_filename(file_path) ⇒ Object



146
147
148
149
# File 'lib/logviewer.rb', line 146

def extract_filename(file_path)
  return '' if file_path.nil? || file_path.empty?
  File.basename(file_path)
end

#find_most_recent_ndjson_fileObject



69
70
71
72
73
74
75
# File 'lib/logviewer.rb', line 69

def find_most_recent_ndjson_file
  ndjson_files = Dir.glob('*.ndjson')
  return nil if ndjson_files.empty?
  
  # Sort by modification time (most recent first) and return the first one
  ndjson_files.max_by { |file| File.mtime(file) }
end

#format_timestamp(timestamp) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
# File 'lib/logviewer.rb', line 134

def format_timestamp(timestamp)
  return '' if timestamp.nil? || timestamp == ''
  
  begin
    # Convert milliseconds to seconds for Time.at
    time = Time.at(timestamp / 1000.0)
    time.strftime('%m/%d %H:%M:%S')
  rescue => e
    timestamp.to_s # fallback to original if parsing fails
  end
end

#generate_html(logs) ⇒ Object



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'lib/logviewer.rb', line 151

def generate_html(logs)
  html = <<~HTML
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Log Viewer - #{File.basename(@input_file)}</title>
        <style>
            body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                margin: 0;
                padding: 20px;
                background-color: #1a1a1a;
                color: #e0e0e0;
            }
            .container {
                max-width: 1800px;
                margin: 0 auto;
                background: #2d2d2d;
                border-radius: 8px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.3);
                overflow: hidden;
            }
            .header {
                background: #1e1e1e;
                color: #f0f0f0;
                padding: 20px;
                text-align: center;
            }
            .header h1 {
                margin: 0;
                font-size: 24px;
            }
            .header p {
                margin: 5px 0 0 0;
                opacity: 0.8;
            }
            .table-container {
                overflow-x: auto;
            }
            table {
                width: 100%;
                border-collapse: collapse;
                font-size: 18px;
                table-layout: fixed;
            }
            th {
                background: #3a3a3a;
                color: #f0f0f0;
                padding: 18px;
                text-align: left;
                font-weight: 600;
                border-bottom: 2px solid #555555;
                position: sticky;
                top: 0;
            }
            td {
                padding: 15px 18px;
                border-bottom: 1px solid #404040;
                vertical-align: top;
                color: #e0e0e0;
            }
            tr:hover {
                background-color: #3a3a3a;
            }
            .level {
                font-weight: bold;
                text-transform: uppercase;
                font-size: 16px;
                white-space: nowrap;
            }
            .text {
                word-wrap: break-word;
                white-space: pre-wrap;
                width: auto;
            }
            .file {
                font-family: 'Monaco', 'Menlo', monospace;
                font-size: 16px;
                color: #b0b0b0;
                max-width: 200px;
                word-wrap: break-word;
            }
            .method {
                font-family: 'Monaco', 'Menlo', monospace;
                font-size: 16px;
                color: #d0d0d0;
                font-weight: 500;
                max-width: 300px;
                word-wrap: break-word;
                overflow-wrap: break-word;
            }
            .timestamp {
                font-family: 'Monaco', 'Menlo', monospace;
                font-size: 15px;
                color: #b0b0b0;
                white-space: nowrap;
            }
            .tag {
                font-family: 'Monaco', 'Menlo', monospace;
                font-size: 16px;
                color: #5dade2;
                font-weight: 500;
                word-wrap: break-word;
                overflow-wrap: break-word;
            }

            .empty {
                color: #777;
                font-style: italic;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>Log Viewer</h1>
                <p>#{File.basename(@input_file)}#{logs.length} entries • Level: #{@min_level.upcase}+</p>
                <div style="margin-top: 15px;">
                    <label for="levelFilter" style="color: white; margin-right: 10px;">Filter by level:</label>
                    <select id="levelFilter" style="padding: 5px; font-size: 14px; border-radius: 4px; border: none; background-color: #3a3a3a; color: #f0f0f0;">
  HTML

# Generate dropdown options only for levels >= command line minimum
min_level_num = LOG_LEVELS[@min_level]
LOG_LEVELS.each do |level, level_num|
  if level_num >= min_level_num
    html += <<~HTML
                        <option value="#{level}">#{level.upcase}+</option>
    HTML
  end
end

html += <<~HTML
                    </select>
                </div>
            </div>
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th style="width: 120px;">Date</th>
                            <th style="width: 80px;">Level</th>
                            <th style="width: 120px;">Tag</th>
                            <th style="width: 180px;">File</th>
                            <th style="width: 300px;">Function</th>
                            <th style="width: auto;">Text</th>
                        </tr>
                    </thead>
                    <tbody>
  HTML

  logs.each do |log|
    level_style = "color: #{level_color(log[:level])}"
    formatted_timestamp = format_timestamp(log[:timestamp])
    timestamp_content = formatted_timestamp.empty? ? '<span class="empty">-</span>' : formatted_timestamp
    tag_content = log[:tag].empty? ? '<span class="empty">-</span>' : log[:tag]
    text_content = log[:text].empty? ? '<span class="empty">-</span>' : log[:text]
    filename = extract_filename(log[:file])
    file_content = filename.empty? ? '<span class="empty">-</span>' : filename
    method_content = log[:method].empty? ? '<span class="empty">-</span>' : log[:method]
    
    html += <<~HTML
                            <tr data-level="#{log[:level].downcase}" data-level-num="#{LOG_LEVELS[log[:level].downcase] || 0}">
                                <td class="timestamp">#{timestamp_content}</td>
                                <td class="level" style="#{level_style}">#{log[:level]}</td>
                                <td class="tag">#{tag_content}</td>
                                <td class="file">#{file_content}</td>
                                <td class="method">#{method_content}</td>
                                <td class="text">#{text_content}</td>
                            </tr>
    HTML
  end

  html += <<~HTML
                    </tbody>
                </table>
            </div>
        </div>
      
        <script>
            const LOG_LEVELS = {
                'trace': 0,
                'debug': 1,
                'info': 2,
                'notice': 3,
                'warning': 4,
                'error': 5,
                'critical': 6
            };
          
            const levelFilter = document.getElementById('levelFilter');
            const tableRows = document.querySelectorAll('tbody tr');
          
            // Set initial filter to match command line parameter
            levelFilter.value = '#{@min_level}';
          
            function filterByLevel() {
                const selectedLevel = levelFilter.value;
                const selectedLevelNum = LOG_LEVELS[selectedLevel];
                let visibleCount = 0;
              
                tableRows.forEach(row => {
                    const rowLevelNum = parseInt(row.dataset.levelNum);
                    if (rowLevelNum >= selectedLevelNum) {
                        row.style.display = '';
                        visibleCount++;
                    } else {
                        row.style.display = 'none';
                    }
                });
              
                // Update the header count
                const header = document.querySelector('.header p');
                const originalText = header.textContent.split(' • ');
                originalText[1] = visibleCount + ' entries';
                originalText[2] = 'Level: ' + selectedLevel.toUpperCase() + '+';
                header.textContent = originalText.join(' • ');
            }
          
            levelFilter.addEventListener('change', filterByLevel);
          
            // Apply initial filter
            filterByLevel();
        </script>
    </body>
    </html>
  HTML

  html
end

#level_color(level) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/logviewer.rb', line 113

def level_color(level)
  case level.downcase
  when 'trace'
    '#adb5bd'
  when 'debug'
    '#adb5bd'
  when 'info'
    '#6ea8fe'
  when 'notice'
    '#ffc107'
  when 'warning'
    '#fd9843'
  when 'error'
    '#ea868f'
  when 'critical'
    '#c29ffa'
  else
    '#e0e0e0'
  end
end

#parse_logsObject



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
111
# File 'lib/logviewer.rb', line 82

def parse_logs
  logs = []
  
  File.foreach(@input_file) do |line|
    begin
      log_entry = JSON.parse(line.strip)
      
      if should_include_log?(log_entry['levelName'])
        # Build tag from subsystem/category
        tag = []
        tag << log_entry['subsystem'] if log_entry['subsystem']
        tag << log_entry['category'] if log_entry['category']
        tag_string = tag.join('/')
        
        logs << {
          timestamp: log_entry['timestamp'] || '',
          level: log_entry['levelName'] || 'unknown',
          tag: tag_string,
          text: log_entry['message'] || '',
          file: log_entry['file'] || '',
          method: log_entry['function'] || ''
        }
      end
    rescue JSON::ParserError => e
      puts "Warning: Skipping invalid JSON line: #{e.message}"
    end
  end
  
  logs
end

#parse_optionsObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/logviewer.rb', line 25

def parse_options
  OptionParser.new do |opts|
    opts.banner = "Usage: logviewer [options] [ndjson_file]"
    
    opts.on('-l', '--level LEVEL', 'Minimum log level (trace, debug, info, notice, warning, error, critical)') do |level|
      level = level.downcase
      if LOG_LEVELS.key?(level)
        @min_level = level
      else
        puts "Invalid log level: #{level}"
        puts "Valid levels: #{LOG_LEVELS.keys.join(', ')}"
        exit 1
      end
    end
    
    opts.on('-v', '--version', 'Show version') do
      puts "logviewer #{LogViewer::VERSION}"
      exit
    end
    
    opts.on('-h', '--help', 'Show this help message') do
      puts opts
      exit
    end
  end.parse!(@args)
  
  if @args.empty?
    @input_file = find_most_recent_ndjson_file
    if @input_file.nil?
      puts "Error: No .ndjson files found in current directory"
      puts "Usage: logviewer [options] [ndjson_file]"
      exit 1
    end
    puts "No file specified, using most recent .ndjson file: #{@input_file}"
  else
    @input_file = @args[0]
  end
  
  unless File.exist?(@input_file)
    puts "Error: File not found: #{@input_file}"
    exit 1
  end
end

#runObject



384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
# File 'lib/logviewer.rb', line 384

def run
  parse_options
  
  puts "Parsing log file: #{@input_file}"
  puts "Minimum log level: #{@min_level}"
  
  logs = parse_logs
  puts "Found #{logs.length} log entries matching criteria"
  
  if logs.empty?
    puts "No log entries found matching the specified criteria."
    exit 0
  end
  
  html_content = generate_html(logs)
  
  # Use /tmp directory for HTML files
  tmp_dir = '/tmp'
  
  # Generate output filename
  base_name = File.basename(@input_file, '.*')
  timestamp = Time.now.strftime('%Y%m%d_%H%M%S')
  output_file = File.join(tmp_dir, "#{base_name}_#{timestamp}.html")
  
  # Write HTML file
  File.write(output_file, html_content)
  puts "HTML file created: #{output_file}"
  
  # Open in browser
  system('open', output_file)
  puts "Opening in browser..."
end

#should_include_log?(level) ⇒ Boolean

Returns:

  • (Boolean)


77
78
79
80
# File 'lib/logviewer.rb', line 77

def should_include_log?(level)
  return true unless level
  LOG_LEVELS[level.downcase] >= LOG_LEVELS[@min_level]
end