module FlogRuby::Floggable

Attributes

group[RW]

Public Instance Methods

flog(level, tag, opts = {}) click to toggle source
# File lib/flog_ruby/logger_factory.rb, line 21
def flog(level, tag, opts = {})
  attrs = (opts || {}).with_indifferent_access
  extra = attrs.delete(:extra) || {}

  opt_tag = attrs.delete(:tag)
  if opt_tag
    extra[:msg] ||= tag
    tag = opt_tag
  end

  # resource
  resource = attrs.delete :resource
  if resource
    attrs[:resource_type] ||= resource.class.name
    attrs[:resource_id] ||= resource&.id
  end

  # distinct_id
  if attrs[:distinct_id].nil?
    attrs[:distinct_id] = attrs[:user_id] ? attrs[:user_id] : attrs[:client_ip]
  end

  # role
  uid = attrs[:user_id]
  attrs[:role] = Flog.user_klass.find_by(id: uid)&.role if attrs[:role].nil? && uid

  # error
  err = extra.delete :error
  extra[:backtrace] = err.backtrace.first(10).join('; ') if err && err.is_a?(Exception)

  # 添加来源信息origin
  origin = ENV.fetch('SYSLOG_ORIGIN', group)

  body = {origin: origin, properties: attrs, extra: extra}.to_json.to_s
  blk = lambda { body }
  clevel = ::Logger.const_get(level.upcase)
  stag = [group, tag].compact.join('_')
  add(clevel, nil, stag, &blk)
  #send "raw_#{level}", nil, &blk
end