As far as I know, the best way to debugg in production with heroku is verifying it's logs. I want to display a variable as a string to this terminal but I couldn't yet with the configuration below.
from the command:
heroku logs
I want to display from a given page's controller something like:
puts "****test****"
this heroku article is saying that it needs to config with:
config.ru
$stdout.sync = true
and I write between these two lines:
require_relative 'config/environment'
$stdout.sync = true # <----
run Rails.application
In the same article, is saying that we need to add config.logger = Logger.new(STDOUT) into "into your app’s configuration to get stdout logging".
So, added inside production.rb between these lines:
# (...)
config.logger = Logger.new(STDOUT) # <---
config.log_level = :debug
config.log_tags = [ :request_id ]
# (...)
That doesn't work.
In your production.rb file you should have this configuration (it should already be there, but doesn't hurt to make sure)
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
This tells you that you need to make sure that the RAILS_LOG_TO_STDOUT environment variable has a value in production.
$ heroku config:set RAILS_LOG_TO_STDOUT=enabled
Then, in your controller, you can call something like
logger.debug "****test****"
Related
I am getting an uninitialized constant ActiveRecord::AssociationNotFoundError (NameError) on my production environment only, development/staging works fine. When I comment out the lines from the code that is running in production, in a docker container by the way, the code runs fine.
I have this exception handler module inside controller/concerns
This module is included by Application Controller
the line:
rescue_from ActiveRecord::AssociationNotFoundError do |e|
json_response({ status: '422', details: [ { message: e.message } ] }, :unprocessable_entity)
end
config/environments/production
Rails.application.configure do
config.cache_classes = true
config.hosts << "www.example.com"
config.hosts << "limpar-api"
config.cache_store = :redis_cache_store, { url: ENV.fetch("REDIS_URL_CACHING", "redis://localhost:6379/0") }
config.eager_load = true
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
config.active_storage.service = :local
config.log_level = :debug
config.log_tags = [ :request_id ]
config.action_mailer.perform_caching = false
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.log_formatter = ::Logger::Formatter.new
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
config.active_record.dump_schema_after_migration = false
end
config/environments/staging
Rails.application.configure do
config.active_record.migration_error = false
config.active_record.verbose_query_logs = true
end
Any idea why?
#queroga_vqz can you update the question with the full code of the included module? I think I now understand the error:
In production rails uses "eager_loading" to load ALL .rb under app/ at app boot time. -> Maybe try changing it in config/environments/development.rb to config.eager_loading = true to have the same behaviour in development for debugging
One idea to resolve: ActiveRecord is not loaded when the concern is loaded (maybe the eager load loaded the controllers before the models?). Fix idea: On top of your concern, try:
require "active_record/all"
# or
require "active_record/associations"
Other Idea, change to AS::Concern with included (if not already):
module ExceptionHandlingConcern
extend ActiveSupport::Concern
included do
rescue_from ...
end
end
There have been many questions over many years where people have this issue. I have tried a combination of answers but I still can't get my updated stylesheet and javascript in my Rails 5.1.6 application to load in Heroku. It works on my local machine.
Here are my files.
app/assets/stylesheets/application.scss
*= require_tree .
*= require_self
app/views/layouts/application.html.erb
<html>
<head>
......
<%= stylesheet_link_tag "application", media: "all" %>
<%= csrf_meta_tags %>
<%= favicon_link_tag "/favicon.ico" %>
<%= render 'layouts/shim' %>
</head>
<body>
......
<%= debug(params) if Rails.env.development? %>
<%= javascript_include_tag "application" %>
</body>
</html>
config/application.rb
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module EzklwRor
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
RouteTranslator.config do |config|
config.generate_unnamed_unlocalized_routes = true
config.locale_param_key = :locale
end
config.exceptions_app = self.routes
config.action_dispatch.default_headers = { 'X-Frame-Options' => 'ALLOWALL' }
end
end
config/environments/production.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# We are using Rails ActionMailers in this application
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
domain: 'www.mydomain.com',
address: ENV["SMTPADDRESS"],
port: 587,
user_name: ENV["SMTPUSERNAME"],
password: ENV["SMTPPASSWORD"],
authentication: 'plain' }
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
# Attempt to read encrypted secrets from `config/secrets.yml.enc`.
# Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or
# `config/secrets.yml.key`.
config.read_encrypted_secrets = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.serve_static_assets = true
config.assets.compile = true
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "ezklw_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = [I18n.default_locale]
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
Here is what I have done on my local machine.
rake assets:clean
rake assets:precompile
rake assets:precompile RAILS_ENV=production
committed changes with public/assets folder included using Github desktop app
git push heroku master
git push heroku master -f when initial change did not work after adding spaces to a file to avoid everything-up-to-date message.
heroku rake assets:precompile RAILS_ENV=production
heroku restart several times along the way
heroku repo:clone -a myapp to verify that my app/assets folder was up to date
heroku repo:reset -a myapp to empty the heroku repo
git push heroku master
heroku logs -t
I have cleared the cache in my browser several times, rebooted my computer and displayed the new app on different devices. I see no errors in the heroku log. My css and js are not working. Where else can I look to fix this?
I checked your configuration files, and in the config/environments/production.rb you have a mistake with config.serve_static_assets = true; therefore, you needed to change to config.public_file_server.enabled = true, and also, please change config.assets.compile = false because I don't think that you want to compile assets with every single request.
Here is similar usage: config/environments/production.rb
For more information please check the same Q&A: https://stackoverflow.com/a/54376240/8929392
I was doing some changes in my app locally and everything was working fine, but after I deployed my app, the stylesheet files are not working. I already cloned the app to check if the files are present, and they are. So I imagine that the problem is in any of my config files.
How is:
How should be:
Here are my config files:
environments/production.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = true
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :local
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "cronograma_capilar_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
config.cache_classes = true
config.serve_static_assets = true
config.assets.compile = true
config.assets.digest = true
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
#config.web_console.whiny_requests = false
config.paperclip_defaults = {
storage: :s3,
s3_credentials: {
bucket: ENV.fetch('S3_BUCKET_NAME'),
access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'),
secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY')
},
s3_region: ENV.fetch('AWS_REGION')
}
Paperclip.options[:image_magick_path] = "/opt/ImageMagick/bin"
Paperclip.options[:command_path] = "/opt/ImageMagick/bin"
end
config/application.rb
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module CronogramaCapilar
class Application < Rails::Application
config.assets.initialize_on_precompile = false
config.assets.paths << "#{Rails}/vendor/assets/fonts"
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
I also tried run the commands bundle exec rake assets:precompile, RAILS_ENV=production rake assets:precompile and not working :(
I recently created a rails app which is hosted in Heroku. When you access the app, both the css and the javascript dont load.
This is the url that is being generated
<link rel="stylesheet" media="all" href="/events/assets/application-9a60e8cdcf689d8333e107c58a2d6fe35cd8367ea14a2911c56898e476dadd09.css" data-turbolinks-track="reload" />
But is shouldn't have the /events/ part added to it.
My CSS and JS are being called from views/layouts/application.html.haml
This is my environments/production.rb file:
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Attempt to read encrypted secrets from `config/secrets.yml.enc`.
# Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or
# `config/secrets.yml.key`.
config.read_encrypted_secrets = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
# config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
config.public_file_server.enabled = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "bmasb_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
config.relative_url_root = "/events"
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
Any help is appreciated!
This line config.relative_url_root = "/events" in your production.rb is prepending the /events to your url. If this is intentional and your app is in events sub directory, something else might be causing the issue. You can run RAILS_ENV=production rake assets:precompile or RAILS_RELATIVE_URL_ROOT=/events RAILS_ENV=production rake assets:precompile locally to get further info about the error.
Did you precompile the assets while uploading to heroku?
RAILS_ENV=production rake assets:precompile
I am making my Rails logger more detailed by adding Time, User ID, and Severity to each log statement.
I created a new file in config/initializers called log_formatter.rb to format the logging messages. Here is the file:
class Logger::Formatter
def call(severity, time, progname, msg)
"#{Time.now.strftime("%F %T").to_s} #{severity} #{msg}\n"
end
end
Rails.configuration.log_tags = [
proc do |req|
if req.session["warden.user.user.key"].nil?
"Anonym"
else
"uid:#{req.session["warden.user.user.key"][0][0]}"
end
end
]
My config/environments/development.rb contains:
Rails.application.configure do
config.log_level = :info
config.log_formatter = Logger::Formatter.new
end
This works perfectly when I am in development and I get an output to the log file of:
2015-12-02 00:33:30 INFO [uid:1] <Message>
My config/environments/production.rb contains:
require_relative './../initializers/log_formatter'
Rails.application.configure do
config.logger = ActiveSupport::Logger.new(STDOUT)
config.log_level = :info
config.log_formatter = Logger::Formatter.new
end
However, while in production, the only message I get is from the log_tags
[uid:1] <Message>
I am not sure what is being changed here, but it looks like the function 'call' is not being called when the logger is being formatted. I have been working on this issue for about a week now, and I would really appreciate the help!
Let me know if you have any clarification questions, and thank you very much!
Looks like you just got a naming clash - Logger::Formatter class is included in Ruby 2.0+, and it got loaded instead of your custom class due to different class loading strategy in production. Just rename your class to e.g. MyLoggerFormatter and it should work:
class MyLoggerFormatter
def call(severity, time, progname, msg)
"#{Time.now.strftime("%F %T").to_s} #{severity} #{msg}\n"
end
end
Rails.application.configure do
config.logger = ActiveSupport::Logger.new(STDOUT)
config.log_level = :info
config.log_formatter = MyLoggerFormatter.new
end
For anyone using GCP, I removed the stackdriver gem and I got my logs back.