Class: Timber::Contexts::User

Inherits:
Timber::Context
  • Object
show all
Defined in:
lib/timber/contexts/user.rb

Overview

The user context tracks the currently authenticated user.

You will want to add this context at the time log the user in, typically during the authentication flow.

Note: Timber will attempt to automatically add this if you add a #current_user method to your controllers. Most authentication solutions do this for you automatically.

Examples:

Basic example

user_context = Timber::Contexts::User.new(id: "abc1234", name: "Ben Johnson")
Timber::CurrentContext.with(user_context) do
  # Logging will automatically include this context
  logger.info("This is a log message")
end

Rails example

class ApplicationController < ActionController::Base
  around_filter :capture_user_context
  private
    def capture_user_context
      if current_user
        user_context = Timber::Contexts::User.new(id: current_user.id,
          name: current_user.name, email: current_user.email)
        Timber::CurrentContext.with(user_context) { yield }
      else
        yield
      end
    end
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes) ⇒ User

Returns a new instance of User.



37
38
39
40
41
# File 'lib/timber/contexts/user.rb', line 37

def initialize(attributes)
  @id = attributes[:id]
  @name = attributes[:name]
  @email = attributes[:email]
end

Instance Attribute Details

#emailObject (readonly)

Returns the value of attribute email.



35
36
37
# File 'lib/timber/contexts/user.rb', line 35

def email
  @email
end

#idObject (readonly)

Returns the value of attribute id.



35
36
37
# File 'lib/timber/contexts/user.rb', line 35

def id
  @id
end

#nameObject (readonly)

Returns the value of attribute name.



35
36
37
# File 'lib/timber/contexts/user.rb', line 35

def name
  @name
end

Instance Method Details

#as_json(_options = {}) ⇒ Object



43
44
45
# File 'lib/timber/contexts/user.rb', line 43

def as_json(_options = {})
  {id: Timber::Util::Object.try(id, :to_s), name: name, email: email}
end