Class: Ferrum::Log

Inherits:
Object
  • Object
show all
Includes:
Paint
Defined in:
lib/ferrum/log.rb,
lib/ferrum/log/json.rb,
lib/ferrum/log/paint.rb,
lib/ferrum/log/default.rb,
lib/ferrum/log/annotated.rb,
sig/ferrum/log.rbs,
sig/ferrum/log/json.rbs,
sig/ferrum/log/paint.rbs,
sig/ferrum/log/default.rbs,
sig/ferrum/log/annotated.rbs

Overview

Writes Ferrum's debug output to the :logger given to Browser.new, split into channels: :protocol (CDP messages) and :browser (the output of the Chrome process Ferrum launched).

The logger can be an IO-like object responding to puts, or a Logger, which gets every line at debug level with ferrum:<channel> as program name. Nothing is built for a disabled channel or a level the Logger skips.

FERRUM_LOG picks what is written, see Log.parse. FERRUM_LOG_FORMAT picks how CDP messages look: json writes them as JSON alone, see Json, and annotated puts the command id and method in front of each message and its response, see Annotated. Without it they look as they always have, see Default.

Written to a terminal, lines are colored with the basic ANSI colors, which terminal themes adapt to light and dark backgrounds. Files, pipes and Loggers get plain text, and so does a terminal when NO_COLOR is set. FERRUM_LOG_COLOR=always or never overrides both.

Logging never breaks the browser: an error while formatting or writing a line, e.g. a closed IO, is reported once and the line skipped.

Defined Under Namespace

Modules: Paint Classes: Annotated, Default, Json

Constant Summary collapse

CHANNELS =

Returns:

  • (Array[Symbol])
%i[protocol browser].freeze
ALL =

Returns:

  • (Array[String])
%w[* 1 true].freeze
OFF =

Returns:

  • (Array[String])
%w[0 false].freeze
FORMATS =

Returns:

{ default: Default, json: Json, annotated: Annotated }.freeze
VALUE_LENGTH =

Returns:

  • (::Integer)
Integer(ENV.fetch("FERRUM_LOG_VALUE_LENGTH", 1024))

Constants included from Paint

Paint::COLORS

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Paint

#color?

Constructor Details

#initialize(logger, channels: CHANNELS, only: [], skip: [], format: :default, color: :auto) ⇒ Log

Returns a new instance of Log.

Parameters:

  • logger (Object)
  • channels: (Array[Symbol]) (defaults to: CHANNELS)
  • only: (Array[String]) (defaults to: [])
  • skip: (Array[String]) (defaults to: [])
  • format: (Symbol) (defaults to: :default)
  • color: (Symbol) (defaults to: :auto)


143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/ferrum/log.rb', line 143

def initialize(logger, channels: CHANNELS, only: [], skip: [], format: :default, color: :auto)
  @logger = logger
  @channels = channels
  @only = only
  @skip = skip
  @color = case color
           when :always then true
           when :never then false
           else logger.respond_to?(:tty?) && logger.tty? && ENV.fetch("NO_COLOR", "").empty?
           end
  @formatter = FORMATS.fetch(format).new(color: @color)
  @commands = Concurrent::Map.new if format == :annotated || only.any? || skip.any?
  @mutex = Mutex.new
end

Instance Attribute Details

#channels ⇒ Array[Symbol] (readonly)

Returns the value of attribute channels.

Returns:

  • (Array[Symbol])


41
42
43
# File 'lib/ferrum/log.rb', line 41

def channels
  @channels
end

#logger ⇒ Object (readonly)

Returns the value of attribute logger.

Returns:

  • (Object)


41
42
43
# File 'lib/ferrum/log.rb', line 41

def logger
  @logger
end

#only ⇒ Array[String] (readonly)

Returns the value of attribute only.

Returns:

  • (Array[String])


41
42
43
# File 'lib/ferrum/log.rb', line 41

def only
  @only
end

#skip ⇒ Array[String] (readonly)

Returns the value of attribute skip.

Returns:

  • (Array[String])


41
42
43
# File 'lib/ferrum/log.rb', line 41

def skip
  @skip
end

Class Method Details

.dump(value) ⇒ String

Encodes a CDP message, or a part of it, as JSON with string values longer than VALUE_LENGTH shortened, e.g. Base64 screenshots. FERRUM_LOG_VALUE_LENGTH=0 keeps them whole. Messages nest as deep as Chrome sends them, e.g. a DOM tree, so there's no nesting limit.

Parameters:

  • value (Object)

Returns:

  • (String)


121
122
123
# File 'lib/ferrum/log.rb', line 121

def self.dump(value)
  JSON.generate(truncate(value), max_nesting: false)
end

.parse(value) ⇒ Hash{Symbol => Array}?

Parses FERRUM_LOG, a comma-separated list of:

  • *, 1 or true - all channels
  • protocol, browser - that channel, -browser leaves it out
  • Page.*, Runtime.evaluate - only CDP messages whose method matches, which turns protocol on
  • -Network.* - leaves out CDP messages whose method matches

Without a channel or CDP pattern to log, all channels are logged, so -browser means everything but the browser output. Exclusions win over inclusions, and responses follow the command they answer. 0, false or an empty value turn logging off.

Parameters:

  • value (String, nil)

Returns:

  • (Hash{Symbol => Array}, nil) —

    The channels:, only: and skip: for #initialize, nil when off.



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/ferrum/log.rb', line 60

def self.parse(value)
  items = value.to_s.split(",").map(&:strip).reject(&:empty?)
  return if items.all? { |item| OFF.include?(item) }

  patterns, names = items.partition { |item| item.include?(".") }
  skip, only = patterns.partition { |pattern| pattern.start_with?("-") }
  removed, added = names.partition { |name| name.start_with?("-") }

  channels = added.flat_map { |name| parse_channel(name) }
  channels << :protocol if only.any?
  channels = CHANNELS if channels.empty?
  channels -= removed.flat_map { |name| parse_channel(name.delete_prefix("-")) }

  { channels: channels.uniq, only: only, skip: skip.map { |pattern| pattern.delete_prefix("-") } }
end

.parse_channel(name) ⇒ Array<Symbol>

Parses one channel item of FERRUM_LOG, warning about an unknown one.

Parameters:

  • name (String)

Returns:

  • (Array<Symbol>)


81
82
83
84
85
86
87
# File 'lib/ferrum/log.rb', line 81

def self.parse_channel(name)
  return CHANNELS if ALL.include?(name)
  return [name.to_sym] if CHANNELS.include?(name.to_sym)

  warn "Ferrum: unknown FERRUM_LOG item #{name.inspect} is ignored"
  []
end

.parse_color(value) ⇒ Symbol

Parses FERRUM_LOG_COLOR, anything but always or never means :auto.

Parameters:

  • value (String, nil)

Returns:

  • (Symbol)


109
110
111
# File 'lib/ferrum/log.rb', line 109

def self.parse_color(value)
  %w[always never].include?(value.to_s.strip) ? value.strip.to_sym : :auto
end

.parse_format(value) ⇒ Symbol

Parses FERRUM_LOG_FORMAT: json, annotated or default, which is also what an empty or unknown value means.

Parameters:

  • value (String, nil)

Returns:

  • (Symbol)


95
96
97
98
99
100
101
102
# File 'lib/ferrum/log.rb', line 95

def self.parse_format(value)
  format = value.to_s.strip
  return :default if format.empty?
  return format.to_sym if FORMATS.key?(format.to_sym)

  warn "Ferrum: unknown FERRUM_LOG_FORMAT #{format.inspect}, using default"
  :default
end

.truncate(value) ⇒ Object

Shortens string values longer than VALUE_LENGTH anywhere in a CDP message.

Parameters:

  • value (Object)

Returns:

  • (Object)


131
132
133
134
135
136
137
138
139
140
141
# File 'lib/ferrum/log.rb', line 131

def self.truncate(value)
  case value
  when Hash then value.transform_values { |item| truncate(item) }
  when Array then value.map { |item| truncate(item) }
  when String
    return value if VALUE_LENGTH.zero? || value.size <= VALUE_LENGTH

    "#{value[0, VALUE_LENGTH]}... (#{value.size - VALUE_LENGTH} more characters)"
  else value
  end
end

Instance Method Details

#browser(line) ⇒ void

This method returns an undefined value.

Writes a line of the browser process output.

Parameters:

  • line (String)


210
211
212
# File 'lib/ferrum/log.rb', line 210

def browser(line)
  write(:browser) { line }
end

#enabled?(channel) ⇒ Boolean

Whether the channel is written to the logger.

Parameters:

  • channel (Symbol)

Returns:

  • (Boolean)


163
164
165
# File 'lib/ferrum/log.rb', line 163

def enabled?(channel)
  channels.include?(channel)
end

#received(message, raw, connection = nil) ⇒ void

This method returns an undefined value.

Writes a CDP message received from the browser.

Parameters:

  • message (Hash{String => Object}, nil) —

    The parsed message, nil when it couldn't be parsed.

  • raw (String) —

    The message as received.

  • connection (Object) (defaults to: nil) —

    What the message was received over.



196
197
198
199
200
201
202
203
# File 'lib/ferrum/log.rb', line 196

def received(message, raw, connection = nil)
  return unless enabled?(:protocol)

  command = answered_command(message, connection)
  return unless show?(message&.fetch("method", nil) || command&.first)

  write(:protocol) { @formatter.received(message, raw, Utils::ElapsedTime.elapsed_time, command) }
end

#sent(message, connection = nil) ⇒ void

This method returns an undefined value.

Writes a CDP message sent to the browser.

Parameters:

  • message (Hash{Symbol => Object})
  • connection (Object) (defaults to: nil) —

    What the message was sent over, command ids are unique per connection.



175
176
177
178
179
180
181
182
# File 'lib/ferrum/log.rb', line 175

def sent(message, connection = nil)
  return unless enabled?(:protocol)

  @commands&.[]=([connection, message[:id]], [message[:method], Utils::ElapsedTime.monotonic_time])
  return unless show?(message[:method])

  write(:protocol) { @formatter.sent(message, Utils::ElapsedTime.elapsed_time) }
end