Skip to content
This repository has been archived by the owner on Dec 8, 2020. It is now read-only.

Commit

Permalink
Modify install and initializer
Browse files Browse the repository at this point in the history
  • Loading branch information
binarylogic committed Mar 22, 2017
1 parent cff4c5b commit 09fe3d8
Show file tree
Hide file tree
Showing 15 changed files with 116 additions and 118 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

* [Timber website](https://timber.io)
* [Timber docs](https://timber.io/docs)
* [Library docs](https://hex.pm/packages/timber)
* [Library docs](http://www.rubydoc.info/github/timberio/timber-ruby)
* [Support](mailto:support@timber.io)


Expand Down
67 changes: 48 additions & 19 deletions lib/timber/cli/install.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,13 @@ def run(api_key)

app = Application.new(api)

puts "Woot! Your API 🔑 is valid. Here are you application details:"
puts ""
puts "Name: #{app.name} (#{app.environment})"
puts "Framework: #{app.framework_type}"
puts "Platform: #{app.platform_type}"
puts ""
puts Messages.application_details(app)

case ask_yes_no("Are the above details correct?")
when :yes
if app.heroku?
create_initializer(:stdout)

puts ""
puts Messages.separator
puts ""
Expand All @@ -55,17 +52,16 @@ def run(api_key)

case ask("Enter your choice: (1/2) ")
when "1"
create_initializer(:http, :api_key_code => "ENV['TIMBER_API_KEY']")

puts ""
puts Messages.http_environment_variables(app.api_key)
puts ""

when "2"
puts ""
write Messages.task_start("Creating config/initializers/timber.rb")

create_initializer("http", app)
create_initializer(:http, :api_key_code => "'#{app.api_key}'")

puts colorize(Messages.task_complete("Creating config/initializers/timber.rb"), :green)
puts ""
end

send_test_messages(api_key)
Expand Down Expand Up @@ -103,17 +99,50 @@ def run(api_key)
end

private
def create_initializer(log_device, app)
body = "config = Timber::Config.instance\n" \
"config.log_device = Timber::LogDevices::HTTP.new(\"#{app.api_key}\")\n\n" \
"# More config options can be found at: https://timber.io/docs/ruby/configuration/\n" \
"#\n" \
"# Question? Need help?\n" \
"# * Docs: https://timber.io/docs\n" \
"# * Support: support@timber.io" \
def create_initializer(log_device_type, options = {})
puts ""
write Messages.task_start("Creating config/initializers/timber.rb")

logger_code = \
case log_device_type
when :http
api_key_code = options[:api_key_code] || raise(ArgumentError.new("the :api_key_code option is required"))
"log_device = Timber::LogDevices::HTTP.new(#{api_key_code})\n" +
"Timber::Logger.new(log_device)"

when :stdout
"Timber::Logger.new(STDOUT)"
end

body = <<-BODY
# Timber.io Ruby Library
#
# ^ ^ ^ ^ ___I_ ^ ^ ^ ^ ^ ^ ^
# /|\\/|\\/|\\ /|\\ /\\-_--\\ /|\\/|\\ /|\\/|\\/|\\ /|\\/|\\
# /|\\/|\\/|\\ /|\\ / \\_-__\\ /|\\/|\\ /|\\/|\\/|\\ /|\\/|\\
# /|\\/|\\/|\\ /|\\ |[]| [] | /|\\/|\\ /|\\/|\\/|\\ /|\\/|\\
#
# Library: http://github.com/timberio/timber-ruby
# Docs: http://www.rubydoc.info/github/timberio/timber-ruby
# Configuration: http://www.rubydoc.info/github/timberio/timber-ruby/Timber/Config
# Support: support@timber.io
logger = case Rails.env
when "development", "test"
logger = Timber::Logger.new(STDOUT)
logger.formatter = Timber::Logger::SimpleFormatter.new
logger
else
#{logger_code}
end
Timber::Frameworks::Rails.set_logger(logger)
BODY

FileUtils.mkdir_p(File.join(Dir.pwd, "config", "initializers"))
File.write(File.join(Dir.pwd, "config/initializers/timber.rb"), body)

puts colorize(Messages.task_complete("Creating config/initializers/timber.rb"), :green)
end

def send_test_messages(api_key)
Expand Down
23 changes: 12 additions & 11 deletions lib/timber/cli/messages.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# encoding: utf-8

module Timber
class CLI
module Messages
Expand All @@ -11,21 +13,21 @@ module Messages
WEBSITE_URL = "https://timber.io"
MAX_LENGTH = 80.freeze

def edit_app_url(app)
"#{APP_URL}"
end

def application_details(app)
message = <<-MESSAGE
Woot! Your API 🔑 is valid. Here are you application details:"
message = <<-MESSAGE
Woot! Your API 🔑 is valid. Here are you application details:
Name: #{app.name}"
Framework: #{app.framework_type}"
Platform: #{app.platform_type}"
Name: #{app.name} (#{app.environment})
Framework: #{app.framework_type}
Platform: #{app.platform_type}
MESSAGE
message.rstrip
end

def edit_app_url(app)
"#{APP_URL}"
end

def bad_experience_message
message = <<-MESSAGE
Bummer! That is certainly not the experience we were going for.
Expand Down Expand Up @@ -55,9 +57,8 @@ def contact

def http_environment_variables(api_key)
message = <<-MESSAGE
Great! Add these environment variables:
Great! Add this variable to your environment:
export TIMBER_LOG_DEVICE="http"
export TIMBER_API_KEY="#{api_key}"
MESSAGE
Expand Down
67 changes: 4 additions & 63 deletions lib/timber/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,20 @@ module Timber
# environment variable. If that is not set, a reasonable default will be chosen. Each
# method documents this.
class Config
class NoLoggerError < StandardError; end

FORM_URL_ENCODED_CONTENT_TYPE = "application/x-www-form-urlencoded".freeze
JSON_CONTENT_TYPE = "application/json".freeze

include Singleton

attr_writer :api_key, :capture_http_bodies, :debug_logger, :log_device, :log_formatter, :logger
attr_writer :capture_http_bodies, :debug_logger, :log_formatter, :logger

def initialize
@capture_http_bodies = true
@capture_http_body_content_types = [FORM_URL_ENCODED_CONTENT_TYPE, JSON_CONTENT_TYPE]
end

# Your Timber API key. Defaults to the `TIMBER_API_KEY` environment variable.
def api_key
@api_key ||= ENV["TIMBER_API_KEY"]
end

# Enables and disables the capturing of HTTP bodies in `Events::HTTPServerRequest`,
# `HTTPClientRequest`, and `HTTPClientRespone`.
def capture_http_bodies?
Expand All @@ -50,69 +47,13 @@ def debug_logger
@debug_logger
end

# This method allows the delegation of the logger method to a given block. This has
# 2 purposes:
#
# 1. It allows us to delegate the logger call to methods like `::Rails.logger`. In
# a rails environment, this is generally the main logger and Timber respects it.
# 2. It allows Timber to call `Config.instance.logger` internally without having to
# worry about the environment. This way each framework can be responsible for setup.
#
# @private
def delegate_logger_to(&block)
@delegate_logger_to = block
end

def environment
ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development"
end

# The target device that logs are written to. Must respond to #write and #close.
#
# Configure this with an environment variable. `TIMBER_LOG_DEVICE`, must be
# one of `stdout` or `http`. If using `http`, you must supply an API key. See
# {api_key}.
def log_device
@log_device ||= case (ENV["TIMBER_LOG_DEVICE"] || "stdout").downcase
when "stdout"
STDOUT
when "http"
Timber::LogDevices::HTTP.new(api_key)
end
end

# Allows you to change the formatter used when logging messages. This is mostly
# used for test and development environments, where you want a plain text formatter
# without the metadata.
def log_formatter
return @log_formatter if defined?(@log_formatter)

@log_formatter = if ["development", "test"].include?(environment)
Logger::SimpleFormatter.new
else
nil
end
end

# This is the logger Timber writes to. It should be set to your global
# logger to keep the logging destination consitent. Please see `delegate_logger_to`
# to delegate this call to another method. This is set to `Rails.logger`
# for rails.
def logger
if @delegate_logger_to
@delegate_logger_to.call
else
@logger ||= begin
logger = Logger.new(log_device)
logger.formatter = log_formatter

if defined?(::ActiveSupport::TaggedLogging)
::ActiveSupport::TaggedLogging.new(logger)
else
logger
end
end
end
@logger || raise(NoLoggerError.new)
end
end
end
17 changes: 12 additions & 5 deletions lib/timber/frameworks/rails.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,30 @@ class Railtie < ::Rails::Railtie
# rails logger. In older rails versions, :initialize_logger attempts to
# log to a file which can raise permissions errors on some systems.
initializer(:timber_logger, before: :initialize_logger) do
Rails.apply_logger(config)
logger = ::ActiveSupport::Logger.new(STDOUT)
Rails.set_logger(logger)
end

# We setup timber after :load_config_initializers because clients can customize
# timber in config/initializers/timber.rb. This enssure their configuration is
# respected.
initializer(:timber_setup, after: :load_config_initializers) do
# Re-apply the logger to respect any configuration set
Rails.apply_logger(config)
Config.instance.delegate_logger_to { ::Rails.logger }
Rails.configure_middlewares(config.app_middleware)
Integrations.integrate!
end
end

def self.apply_logger(config)
::Rails.logger = config.logger = Config.instance.logger
def self.set_logger(logger)
if defined?(::ActiveSupport::TaggedLogging) && !logger.is_a?(::ActiveSupport::TaggedLogging)
logger = ::ActiveSupport::TaggedLogging.new(logger)
end

Config.instance.logger = logger
::ActionController::Base.logger = logger
::ActionView::Base.logger = logger if ::ActionView::Base.respond_to?(:logger=)
::ActiveRecord::Base.logger = logger
::Rails.logger = logger
end

def self.configure_middlewares(middleware)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def initialize
def integrate!
return true if Util::ActiveSupportLogSubscriber.subscribed?(:action_controller, TimberLogSubscriber)

Util::ActiveSupportLogSubscriber.unsubscribe(:action_controller, ::ActionController::LogSubscriber)
Util::ActiveSupportLogSubscriber.unsubscribe!(:action_controller, ::ActionController::LogSubscriber)
TimberLogSubscriber.attach_to(:action_controller)
end
end
Expand Down
4 changes: 2 additions & 2 deletions lib/timber/integrations/action_view/log_subscriber.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ def initialize
end

def integrate!
return true if Util::ActiveSupportLogSubscriber.subscribed?(:action_view, LogSubscriber)
return true if Util::ActiveSupportLogSubscriber.subscribed?(:action_view, TimberLogSubscriber)

Util::ActiveSupportLogSubscriber.unsubscribe(:action_view, ::ActionView::LogSubscriber)
Util::ActiveSupportLogSubscriber.unsubscribe!(:action_view, ::ActionView::LogSubscriber)
TimberLogSubscriber.attach_to(:action_view)
end
end
Expand Down
4 changes: 2 additions & 2 deletions lib/timber/integrations/active_record/log_subscriber.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ def initialize
end

def integrate!
return true if Util::ActiveSupportLogSubscriber.subscribed?(:active_record, LogSubscriber)
return true if Util::ActiveSupportLogSubscriber.subscribed?(:active_record, TimberLogSubscriber)

Util::ActiveSupportLogSubscriber.unsubscribe(:active_record, ::ActiveRecord::LogSubscriber)
Util::ActiveSupportLogSubscriber.unsubscribe!(:active_record, ::ActiveRecord::LogSubscriber)
TimberLogSubscriber.attach_to(:active_record)
end
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class LogSubscriber < Integrator
# @private
class TimberLogSubscriber < ::ActiveRecord::LogSubscriber
def sql(event)
super(event)
r = super(event)

if @message
payload = event.payload
Expand All @@ -21,7 +21,11 @@ def sql(event)
)

logger.debug event

@message = nil
end

r
end

private
Expand Down
2 changes: 1 addition & 1 deletion lib/timber/log_devices/http.rb
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def push(obj)
# request_queue: Timber::LogDevices::HTTP::DroppingSizedQueue.new(3))
# Timber::Logger.new(http_log_device)
def initialize(api_key, options = {})
@api_key = api_key
@api_key = api_key || raise(ArgumentError.new("The api_key parameter cannot be blank"))
@timber_url = URI.parse(options[:timber_url] || ENV['TIMBER_URL'] || TIMBER_URL)
@batch_size = options[:batch_size] || 1_000
@flush_interval = options[:flush_interval] || 1 # 1 second
Expand Down
1 change: 1 addition & 0 deletions lib/timber/logger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ def extract_active_support_tagged_logging_tags
# For use in development and test environments where you do not want metadata
# included in the log lines.
class SimpleFormatter < Formatter

# This method is invoked when a log event occurs
def call(severity, timestamp, progname, msg)
"#{String === msg ? msg : msg.inspect}\n"
Expand Down
1 change: 1 addition & 0 deletions lib/timber/overrides.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require "timber/overrides/lograge"
require "timber/overrides/rails_server"
require "timber/overrides/rails_stdout_logging"

module Timber
Expand Down
15 changes: 15 additions & 0 deletions lib/timber/overrides/rails_server.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
require "rails/commands/server"

class ::Rails::Server < ::Rack::Server
def initialize(*)
raise "test"
r = super
raise "wtf"
options[:log_to_stdout] = false
r
end

private
def log_to_stdout
end
end
Loading

0 comments on commit 09fe3d8

Please sign in to comment.