Commit 7e13e968aa96a00bc336a1325b07f996b203b814
Committed by
Rodrigo Souto
1 parent
c18fefcf
Exists in
master
and in
29 other branches
api: improve api logging
Showing
4 changed files
with
29 additions
and
15 deletions
Show diff stats
Gemfile
lib/noosfero/api/api.rb
| ... | ... | @@ -6,12 +6,18 @@ module Noosfero |
| 6 | 6 | class API < Grape::API |
| 7 | 7 | use Rack::JSONP |
| 8 | 8 | |
| 9 | - before { start_log } | |
| 9 | + logger = Logger.new(File.join(Rails.root, 'log', "#{ENV['RAILS_ENV'] || 'production'}_api.log")) | |
| 10 | + logger.formatter = GrapeLogging::Formatters::Default.new | |
| 11 | + use RequestLogger, { logger: logger } | |
| 12 | + | |
| 13 | + rescue_from :all do |e| | |
| 14 | + logger.error e | |
| 15 | + end | |
| 16 | + | |
| 10 | 17 | before { setup_multitenancy } |
| 11 | 18 | before { detect_stuff_by_domain } |
| 12 | - after { end_log } | |
| 13 | 19 | after { set_session_cookie } |
| 14 | - | |
| 20 | + | |
| 15 | 21 | version 'v1' |
| 16 | 22 | prefix "api" |
| 17 | 23 | format :json | ... | ... |
lib/noosfero/api/helpers.rb
| ... | ... | @@ -3,11 +3,7 @@ module Noosfero |
| 3 | 3 | module APIHelpers |
| 4 | 4 | PRIVATE_TOKEN_PARAM = :private_token |
| 5 | 5 | ALLOWED_PARAMETERS = ['parent_id', 'from', 'until', 'content_type'] |
| 6 | - | |
| 7 | - def logger | |
| 8 | - @logger ||= Logger.new(File.join(Rails.root, 'log', "#{ENV['RAILS_ENV']}_api.log")) | |
| 9 | - end | |
| 10 | - | |
| 6 | + | |
| 11 | 7 | def current_user |
| 12 | 8 | private_token = (params[PRIVATE_TOKEN_PARAM] || headers['Private-Token'] || cookies['_noosfero_api_session']).to_s if params |
| 13 | 9 | @current_user ||= User.find_by_private_token(private_token) |
| ... | ... | @@ -151,13 +147,6 @@ module Noosfero |
| 151 | 147 | cookies['_noosfero_api_session'] = { value: @current_user.private_token, httponly: true } if @current_user.present? |
| 152 | 148 | end |
| 153 | 149 | |
| 154 | - def start_log | |
| 155 | - logger.info "Started #{request.path} #{request.params.except('password')}" | |
| 156 | - end | |
| 157 | - def end_log | |
| 158 | - logger.info "Completed #{request.path}" | |
| 159 | - end | |
| 160 | - | |
| 161 | 150 | def setup_multitenancy |
| 162 | 151 | Noosfero::MultiTenancy.setup!(request.host) |
| 163 | 152 | end | ... | ... |
| ... | ... | @@ -0,0 +1,18 @@ |
| 1 | +module Noosfero | |
| 2 | + module API | |
| 3 | + class RequestLogger < GrapeLogging::Middleware::RequestLogger | |
| 4 | + | |
| 5 | + protected | |
| 6 | + | |
| 7 | + def parameters(response, duration) | |
| 8 | + { | |
| 9 | + path: request.path, | |
| 10 | + params: request.params.except('password'), | |
| 11 | + method: request.request_method, | |
| 12 | + total: (duration * 1000).round(2), | |
| 13 | + db: request.env[:db_duration].round(2), | |
| 14 | + } | |
| 15 | + end | |
| 16 | + end | |
| 17 | + end | |
| 18 | +end | ... | ... |