Class: Fluent::Log

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

Direct Known Subclasses

PluginLogger

Defined Under Namespace

Modules: TTYColor

Constant Summary collapse

LEVEL_TRACE =
0
LEVEL_DEBUG =
1
LEVEL_INFO =
2
LEVEL_WARN =
3
LEVEL_ERROR =
4
LEVEL_FATAL =
5
LEVEL_TEXT =
%w(trace debug info warn error fatal)
LOG_EVENT_TAG_PREFIX =
'fluent'
LOG_EVENT_LABEL =
'@FLUENT_LOG'
LOG_TYPE_SUPERVISOR =

only in supervisor, or a worker with –no-supervisor

:supervisor
LOG_TYPE_WORKER0 =

only in a worker with worker_id=0 (without showing worker id)

:worker0
LOG_TYPE_DEFAULT =

show logs in all supervisor/workers, with worker id in workers (default)

:default
LOG_TYPES =
[LOG_TYPE_SUPERVISOR, LOG_TYPE_WORKER0, LOG_TYPE_DEFAULT].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger, opts = {}) ⇒ Log

Returns a new instance of Log.



69
70
71
72
73
74
75
76
77
78
79
80
81
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/fluent/log.rb', line 69

def initialize(logger, opts={})
  # overwrites logger.level= so that config reloading resets level of Fluentd::Log
  orig_logger_level_setter = logger.class.public_instance_method(:level=).bind(logger)
  me = self
  # The original ruby logger sets the number as each log level like below.
  # DEBUG = 0
  # INFO  = 1
  # WARN  = 2
  # ERROR = 3
  # FATAL = 4
  # Serverengine use this original log number. In addition to this, serverengine sets -1 as TRACE level.
  # TRACE = -1
  #
  # On the other hand, in fluentd side, it sets the number like below.
  # TRACE = 0
  # DEBUG = 1
  # INFO  = 2
  # WARN  = 3
  # ERROR = 4
  # FATAL = 5
  #
  # Then fluentd's level is set as serverengine's level + 1.
  # So if serverengine's logger level is changed, fluentd's log level will be changed to that + 1.
  logger.define_singleton_method(:level=) {|level| orig_logger_level_setter.call(level); me.level = self.level + 1 }

  @logger = logger
  @out = logger.instance_variable_get(:@logdev)
  @level = logger.level + 1
  @debug_mode = false
  @log_event_enabled = false
  @depth_offset = 1
  @format = nil
  @time_format = nil
  @formatter = nil

  self.format = :text
  enable_color out.tty?
  # TODO: This variable name is unclear so we should change to better name.
  @threads_exclude_events = []

  # Fluent::Engine requires Fluent::Log, so we must take that object lazily
  @engine = Fluent.const_get('Engine')
  @optional_header = nil
  @optional_attrs = nil

  @suppress_repeated_stacktrace = opts[:suppress_repeated_stacktrace]

  @process_type = opts[:process_type] # :supervisor, :worker0, :workers Or :standalone
  @process_type ||= :standalone # to keep behavior of existing code
  case @process_type
  when :supervisor
    @show_supervisor_log = true
    @show_worker0_log = false
  when :worker0
    @show_supervisor_log = false
    @show_worker0_log = true
  when :workers
    @show_supervisor_log = false
    @show_worker0_log = false
  when :standalone
    @show_supervisor_log = true
    @show_worker0_log = true
  else
    raise "BUG: unknown process type for logger:#{@process_type}"
  end
  @worker_id = opts[:worker_id]
  @worker_id_part = "##{@worker_id} " # used only for :default log type in workers
end

Instance Attribute Details

#formatObject

Returns the value of attribute format.



150
151
152
# File 'lib/fluent/log.rb', line 150

def format
  @format
end

#levelObject

Returns the value of attribute level.



153
154
155
# File 'lib/fluent/log.rb', line 153

def level
  @level
end

#log_event_enabledObject

Returns the value of attribute log_event_enabled.



151
152
153
# File 'lib/fluent/log.rb', line 151

def log_event_enabled
  @log_event_enabled
end

#optional_attrsObject

Returns the value of attribute optional_attrs.



155
156
157
# File 'lib/fluent/log.rb', line 155

def optional_attrs
  @optional_attrs
end

#optional_headerObject

Returns the value of attribute optional_header.



155
156
157
# File 'lib/fluent/log.rb', line 155

def optional_header
  @optional_header
end

#outObject

Returns the value of attribute out.



152
153
154
# File 'lib/fluent/log.rb', line 152

def out
  @out
end

#time_formatObject

Returns the value of attribute time_format.



154
155
156
# File 'lib/fluent/log.rb', line 154

def time_format
  @time_format
end

Class Method Details

.event_tagsObject



65
66
67
# File 'lib/fluent/log.rb', line 65

def self.event_tags
  LEVEL_TEXT.map{|t| "#{LOG_EVENT_TAG_PREFIX}.#{t}" }
end

.str_to_level(log_level_str) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/fluent/log.rb', line 53

def self.str_to_level(log_level_str)
  case log_level_str.downcase
  when "trace" then LEVEL_TRACE
  when "debug" then LEVEL_DEBUG
  when "info"  then LEVEL_INFO
  when "warn"  then LEVEL_WARN
  when "error" then LEVEL_ERROR
  when "fatal" then LEVEL_FATAL
  else raise "Unknown log level: level = #{log_level_str}"
  end
end

Instance Method Details

#caller_line(type, time, depth, level) ⇒ Object



488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# File 'lib/fluent/log.rb', line 488

def caller_line(type, time, depth, level)
  worker_id_part = if type == :default && (@process_type == :worker0 || @process_type == :workers)
                     @worker_id_part
                   else
                     "".freeze
                   end
  log_msg = "#{time.strftime(@time_format)} [#{LEVEL_TEXT[level]}]: #{worker_id_part}"
  if @debug_mode
    line = caller(depth+1)[0]
    if match = /^(.+?):(\d+)(?::in `(.*)')?/.match(line)
      file = match[1].split('/')[-2,2].join('/')
      line = match[2]
      method = match[3]
      return "#{log_msg}#{file}:#{line}:#{method}: "
    end
  end
  return log_msg
end

#debug(*args, &block) ⇒ Object Also known as: DEBUG



290
291
292
293
294
295
296
297
298
# File 'lib/fluent/log.rb', line 290

def debug(*args, &block)
  return if @level > LEVEL_DEBUG
  type = log_type(args)
  return if skipped_type?(type)
  args << block.call if block
  time, msg = event(:debug, args)
  puts [@color_debug, @formatter.call(type, time, LEVEL_DEBUG, msg), @color_reset].join
rescue
end

#debug_backtrace(backtrace = $!.backtrace, type: :default) ⇒ Object



301
302
303
# File 'lib/fluent/log.rb', line 301

def debug_backtrace(backtrace=$!.backtrace, type: :default)
  dump_stacktrace(type, backtrace, LEVEL_DEBUG)
end

#disable_events(thread) ⇒ Object

If you want to suppress event emitting in specific thread, please use this method. Events in passed thread are never emitted.



212
213
214
215
# File 'lib/fluent/log.rb', line 212

def disable_events(thread)
  # this method is not symmetric with #enable_event.
  @threads_exclude_events.push(thread) unless @threads_exclude_events.include?(thread)
end

#dump_stacktrace(type, backtrace, level) ⇒ Object



409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# File 'lib/fluent/log.rb', line 409

def dump_stacktrace(type, backtrace, level)
  return if @level > level

  time = Time.now

  if @format == :text
    line = caller_line(type, time, 5, level)
    if @suppress_repeated_stacktrace && (Thread.current[:last_repeated_stacktrace] == backtrace)
      puts ["  ", line, 'suppressed same stacktrace'].join
    else
      backtrace.each { |msg|
        puts ["  ", line, msg].join
      }
      Thread.current[:last_repeated_stacktrace] = backtrace if @suppress_repeated_stacktrace
    end
  else
    r = {
      'time' => time.strftime(@time_format),
      'level' => LEVEL_TEXT[level],
    }
    if wid = get_worker_id(type)
      r['worker_id'] = wid
    end

    if @suppress_repeated_stacktrace && (Thread.current[:last_repeated_stacktrace] == backtrace)
      r['message'] = 'suppressed same stacktrace'
    else
      r['message'] = backtrace.join("\n")
      Thread.current[:last_repeated_stacktrace] = backtrace if @suppress_repeated_stacktrace
    end

    puts Yajl.dump(r)
  end

  nil
end

#dupObject



138
139
140
141
142
143
144
145
146
147
148
# File 'lib/fluent/log.rb', line 138

def dup
  dl_opts = {}
  dl_opts[:log_level] = @level - 1
  logger = ServerEngine::DaemonLogger.new(@out, dl_opts)
  clone = self.class.new(logger, suppress_repeated_stacktrace: @suppress_repeated_stacktrace, process_type: @process_type, worker_id: @worker_id)
  clone.format = @format
  clone.time_format = @time_format
  clone.log_event_enabled = @log_event_enabled
  # optional headers/attrs are not copied, because new PluginLogger should have another one of it
  clone
end

#enable_color(b = true) ⇒ Object



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/fluent/log.rb', line 221

def enable_color(b=true)
  if b
    @color_trace = TTYColor::BLUE
    @color_debug = TTYColor::WHITE
    @color_info  = TTYColor::GREEN
    @color_warn  = TTYColor::YELLOW
    @color_error = TTYColor::MAGENTA
    @color_fatal = TTYColor::RED
    @color_reset = TTYColor::NORMAL
  else
    @color_trace = ''
    @color_debug = ''
    @color_info  = ''
    @color_warn  = ''
    @color_error = ''
    @color_fatal = ''
    @color_reset = ''
  end
  self
end

#enable_color?Boolean

Returns:

  • (Boolean)


217
218
219
# File 'lib/fluent/log.rb', line 217

def enable_color?
  !@color_reset.empty?
end

#enable_debug(b = true) ⇒ Object



200
201
202
203
# File 'lib/fluent/log.rb', line 200

def enable_debug(b=true)
  @debug_mode = b
  self
end

#enable_event(b = true) ⇒ Object



205
206
207
208
# File 'lib/fluent/log.rb', line 205

def enable_event(b=true)
  @log_event_enabled = b
  self
end

#error(*args, &block) ⇒ Object Also known as: ERROR



350
351
352
353
354
355
356
357
358
# File 'lib/fluent/log.rb', line 350

def error(*args, &block)
  return if @level > LEVEL_ERROR
  type = log_type(args)
  return if skipped_type?(type)
  args << block.call if block
  time, msg = event(:error, args)
  puts [@color_error, @formatter.call(type, time, LEVEL_ERROR, msg), @color_reset].join
rescue
end

#error_backtrace(backtrace = $!.backtrace, type: :default) ⇒ Object



361
362
363
# File 'lib/fluent/log.rb', line 361

def error_backtrace(backtrace=$!.backtrace, type: :default)
  dump_stacktrace(type, backtrace, LEVEL_ERROR)
end

#event(level, args) ⇒ Object



454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# File 'lib/fluent/log.rb', line 454

def event(level, args)
  time = Time.now
  message = @optional_header ? @optional_header.dup : ''
  map = @optional_attrs ? @optional_attrs.dup : {}
  args.each {|a|
    if a.is_a?(Hash)
      a.each_pair {|k,v|
        map[k.to_s] = v
      }
    else
      message << a.to_s
    end
  }

  map.each_pair {|k,v|
    if k == "error".freeze && v.is_a?(Exception) && !map.has_key?("error_class")
      message << " error_class=#{v.class.to_s} error=#{v.to_s.inspect}"
    else
      message << " #{k}=#{v.inspect}"
    end
  }

  if @log_event_enabled && !@threads_exclude_events.include?(Thread.current)
    record = map.dup
    record.keys.each {|key|
      record[key] = record[key].inspect unless record[key].respond_to?(:to_msgpack)
    }
    record['message'] = message.dup
    @engine.push_log_event("#{LOG_EVENT_TAG_PREFIX}.#{level}", Fluent::EventTime.from_time(time), record)
  end

  return time, message
end

#fatal(*args, &block) ⇒ Object Also known as: FATAL



370
371
372
373
374
375
376
377
378
# File 'lib/fluent/log.rb', line 370

def fatal(*args, &block)
  return if @level > LEVEL_FATAL
  type = log_type(args)
  return if skipped_type?(type)
  args << block.call if block
  time, msg = event(:fatal, args)
  puts [@color_fatal, @formatter.call(type, time, LEVEL_FATAL, msg), @color_reset].join
rescue
end

#fatal_backtrace(backtrace = $!.backtrace, type: :default) ⇒ Object



381
382
383
# File 'lib/fluent/log.rb', line 381

def fatal_backtrace(backtrace=$!.backtrace, type: :default)
  dump_stacktrace(type, backtrace, LEVEL_FATAL)
end

#flushObject



401
402
403
# File 'lib/fluent/log.rb', line 401

def flush
  @out.flush
end

#get_worker_id(type) ⇒ Object



446
447
448
449
450
451
452
# File 'lib/fluent/log.rb', line 446

def get_worker_id(type)
  if type == :default && (@process_type == :worker0 || @process_type == :workers)
    @worker_id
  else
    nil
  end
end

#info(*args, &block) ⇒ Object Also known as: INFO



310
311
312
313
314
315
316
317
318
# File 'lib/fluent/log.rb', line 310

def info(*args, &block)
  return if @level > LEVEL_INFO
  type = log_type(args)
  return if skipped_type?(type)
  args << block.call if block
  time, msg = event(:info, args)
  puts [@color_info, @formatter.call(type, time, LEVEL_INFO, msg), @color_reset].join
rescue
end

#info_backtrace(backtrace = $!.backtrace, type: :default) ⇒ Object



321
322
323
# File 'lib/fluent/log.rb', line 321

def info_backtrace(backtrace=$!.backtrace, type: :default)
  dump_stacktrace(type, backtrace, LEVEL_INFO)
end

#log_type(args) ⇒ Object



242
243
244
245
246
247
248
# File 'lib/fluent/log.rb', line 242

def log_type(args)
  if LOG_TYPES.include?(args.first)
    args.shift
  else
    LOG_TYPE_DEFAULT
  end
end

#logdev=(logdev) ⇒ Object



157
158
159
160
161
# File 'lib/fluent/log.rb', line 157

def logdev=(logdev)
  @out = logdev
  @logger.instance_variable_set(:@logdev, logdev)
  nil
end

#on_debug(&block) ⇒ Object



285
286
287
288
# File 'lib/fluent/log.rb', line 285

def on_debug(&block)
  return if @level > LEVEL_DEBUG
  block.call if block
end

#on_error(&block) ⇒ Object



345
346
347
348
# File 'lib/fluent/log.rb', line 345

def on_error(&block)
  return if @level > LEVEL_ERROR
  block.call if block
end

#on_fatal(&block) ⇒ Object



365
366
367
368
# File 'lib/fluent/log.rb', line 365

def on_fatal(&block)
  return if @level > LEVEL_FATAL
  block.call if block
end

#on_info(&block) ⇒ Object



305
306
307
308
# File 'lib/fluent/log.rb', line 305

def on_info(&block)
  return if @level > LEVEL_INFO
  block.call if block
end

#on_trace(&block) ⇒ Object



264
265
266
267
# File 'lib/fluent/log.rb', line 264

def on_trace(&block)
  return if @level > LEVEL_TRACE
  block.call if block
end

#on_warn(&block) ⇒ Object



325
326
327
328
# File 'lib/fluent/log.rb', line 325

def on_warn(&block)
  return if @level > LEVEL_WARN
  block.call if block
end

#puts(msg) ⇒ Object



385
386
387
388
389
390
391
392
# File 'lib/fluent/log.rb', line 385

def puts(msg)
  @logger << msg + "\n"
  @out.flush
  msg
rescue
  # FIXME
  nil
end

#reopen!Object



194
195
196
197
198
# File 'lib/fluent/log.rb', line 194

def reopen!
  # do nothing in @logger.reopen! because it's already reopened in Supervisor.load_config
  @logger.reopen! if @logger
  nil
end

#resetObject



405
406
407
# File 'lib/fluent/log.rb', line 405

def reset
  @out.reset if @out.respond_to?(:reset)
end

#skipped_type?(type) ⇒ Boolean

TODO: skip :worker0 logs when Fluentd gracefully restarted

Returns:

  • (Boolean)


251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/fluent/log.rb', line 251

def skipped_type?(type)
  case type
  when LOG_TYPE_DEFAULT
    false
  when LOG_TYPE_WORKER0
    !@show_worker0_log
  when LOG_TYPE_SUPERVISOR
    !@show_supervisor_log
  else
    raise "BUG: unknown log type:#{type}"
  end
end

#trace(*args, &block) ⇒ Object Also known as: TRACE



269
270
271
272
273
274
275
276
277
278
# File 'lib/fluent/log.rb', line 269

def trace(*args, &block)
  return if @level > LEVEL_TRACE
  type = log_type(args)
  return if skipped_type?(type)
  args << block.call if block
  time, msg = event(:trace, args)
  puts [@color_trace, @formatter.call(type, time, LEVEL_TRACE, msg), @color_reset].join
rescue
  # logger should not raise an exception. This rescue prevents unexpected behaviour.
end

#trace_backtrace(backtrace = $!.backtrace, type: :default) ⇒ Object



281
282
283
# File 'lib/fluent/log.rb', line 281

def trace_backtrace(backtrace=$!.backtrace, type: :default)
  dump_stacktrace(type, backtrace, LEVEL_TRACE)
end

#warn(*args, &block) ⇒ Object Also known as: WARN



330
331
332
333
334
335
336
337
338
# File 'lib/fluent/log.rb', line 330

def warn(*args, &block)
  return if @level > LEVEL_WARN
  type = log_type(args)
  return if skipped_type?(type)
  args << block.call if block
  time, msg = event(:warn, args)
  puts [@color_warn, @formatter.call(type, time, LEVEL_WARN, msg), @color_reset].join
rescue
end

#warn_backtrace(backtrace = $!.backtrace, type: :default) ⇒ Object



341
342
343
# File 'lib/fluent/log.rb', line 341

def warn_backtrace(backtrace=$!.backtrace, type: :default)
  dump_stacktrace(type, backtrace, LEVEL_WARN)
end

#write(data) ⇒ Object Also known as: <<



394
395
396
# File 'lib/fluent/log.rb', line 394

def write(data)
  @out.write(data)
end