Class: Msf::MCP::Logging::Sinks::JsonStream

Inherits:
Object
  • Object
show all
Includes:
Rex::Logging::LogSink
Defined in:
lib/msf/core/mcp/logging/sinks/json_stream.rb

Overview

A Rex LogSink that formats log messages as JSON and writes them to an IO stream (e.g. $stdout, a File, a StringIO).

Examples:

Writing JSON logs to $stderr

sink = Msf::MCP::Logging::Sinks::JsonStream.new($stderr)
register_log_source('mcp', sink, Rex::Logging::LEV_0)

Backed by a file via JsonFlatfile

sink = Msf::MCP::Logging::Sinks::JsonFlatfile.new('msfmcp.log')
register_log_source('mcp', sink, Rex::Logging::LEV_0)

Direct Known Subclasses

JsonFlatfile

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Rex::Logging::LogSink

#get_current_timestamp

Constructor Details

#initialize(stream) ⇒ JsonStream

Returns a new instance of JsonStream.



19
20
21
# File 'lib/msf/core/mcp/logging/sinks/json_stream.rb', line 19

def initialize(stream)
  @stream = stream
end

Instance Attribute Details

#streamObject (protected)

Returns the value of attribute stream.



64
65
66
# File 'lib/msf/core/mcp/logging/sinks/json_stream.rb', line 64

def stream
  @stream
end

Instance Method Details

#cleanupObject



58
59
60
# File 'lib/msf/core/mcp/logging/sinks/json_stream.rb', line 58

def cleanup
  stream.close
end

#log(sev, src, level, msg) ⇒ Object



23
24
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
# File 'lib/msf/core/mcp/logging/sinks/json_stream.rb', line 23

def log(sev, src, level, msg)
  log_entry = {
    timestamp: get_current_timestamp,
    severity: sev.to_s.upcase,
    level: level.to_s,
    source: src.to_s,
    message: msg.to_s
  }

  if msg.is_a?(Hash)
    log_entry[:message] = msg[:message] if msg[:message] && !msg[:message].empty?
    if msg[:context] && !msg[:context].empty?
      log_entry[:context] = if debug_log_level?
                              msg[:context]
                            else
                              summarize_context(msg[:context])
                            end
    end
    if msg[:exception]
      log_entry[:exception] = if msg[:exception].is_a?(Exception)
                                ex_msg = { class: msg[:exception].class.name, message: msg[:exception].message }
                                if get_log_level(LOG_SOURCE) >= BACKTRACE_LOG_LEVEL
                                  ex_msg[:backtrace] = msg[:exception].backtrace&.first(5) || []
                                end
                                ex_msg
                              else
                                msg[:exception]
                              end
    end
  end

  stream.write(log_entry.to_json + "\n")
  stream.flush
end