├── .ruby-version
├── example
└── rails5
│ ├── lib
│ ├── assets
│ │ └── .keep
│ └── tasks
│ │ └── .keep
│ ├── public
│ ├── favicon.ico
│ ├── apple-touch-icon.png
│ ├── apple-touch-icon-precomposed.png
│ ├── profile.png
│ ├── robots.txt
│ ├── 500.html
│ ├── 422.html
│ └── 404.html
│ ├── app
│ ├── assets
│ │ ├── images
│ │ │ └── .keep
│ │ ├── javascripts
│ │ │ ├── channels
│ │ │ │ └── .keep
│ │ │ ├── hello.coffee
│ │ │ ├── cable.js
│ │ │ └── application.js
│ │ ├── config
│ │ │ └── manifest.js
│ │ └── stylesheets
│ │ │ ├── hello.scss
│ │ │ └── application.css
│ ├── models
│ │ ├── concerns
│ │ │ └── .keep
│ │ └── application_record.rb
│ ├── controllers
│ │ ├── concerns
│ │ │ └── .keep
│ │ ├── application_controller.rb
│ │ └── hello_controller.rb
│ ├── views
│ │ ├── layouts
│ │ │ ├── mailer.text.erb
│ │ │ ├── mailer.html.erb
│ │ │ └── application.html.erb
│ │ └── hello
│ │ │ └── index.html.erb
│ ├── helpers
│ │ ├── hello_helper.rb
│ │ └── application_helper.rb
│ ├── jobs
│ │ └── application_job.rb
│ ├── channels
│ │ └── application_cable
│ │ │ ├── channel.rb
│ │ │ └── connection.rb
│ └── mailers
│ │ └── application_mailer.rb
│ ├── vendor
│ └── assets
│ │ ├── javascripts
│ │ └── .keep
│ │ └── stylesheets
│ │ └── .keep
│ ├── config
│ ├── initializers
│ │ ├── fluent_logger.rb
│ │ ├── session_store.rb
│ │ ├── mime_types.rb
│ │ ├── application_controller_renderer.rb
│ │ ├── filter_parameter_logging.rb
│ │ ├── cookies_serializer.rb
│ │ ├── rack-action_logger.rb
│ │ ├── backtrace_silencers.rb
│ │ ├── assets.rb
│ │ ├── wrap_parameters.rb
│ │ ├── inflections.rb
│ │ └── new_framework_defaults.rb
│ ├── routes.rb
│ ├── spring.rb
│ ├── boot.rb
│ ├── environment.rb
│ ├── cable.yml
│ ├── application.rb
│ ├── database.yml
│ ├── locales
│ │ └── en.yml
│ ├── secrets.yml
│ ├── environments
│ │ ├── test.rb
│ │ ├── development.rb
│ │ └── production.rb
│ └── puma.rb
│ ├── bin
│ ├── bundle
│ ├── rails
│ ├── rake
│ ├── rspec
│ ├── update
│ └── setup
│ ├── config.ru
│ ├── Rakefile
│ ├── spec
│ ├── controllers
│ │ └── hello_controller_spec.rb
│ ├── rails_helper.rb
│ └── spec_helper.rb
│ ├── .rakeTasks
│ ├── db
│ ├── seeds.rb
│ └── schema.rb
│ ├── README.md
│ ├── .gitignore
│ ├── Gemfile
│ └── Gemfile.lock
├── .rspec
├── docs
├── action_log.png
├── request_log.png
├── sample_log.png
└── attributed_log.png
├── .travis.yml
├── lib
└── rack
│ ├── action_logger
│ ├── version.rb
│ ├── controller_concerns.rb
│ ├── emit_adapter
│ │ ├── null_adapter.rb
│ │ ├── fluent_adapter.rb
│ │ ├── base.rb
│ │ └── logger_adapter.rb
│ ├── metrics.rb
│ ├── emit_adapter.rb
│ ├── context.rb
│ ├── parameter_filtering.rb
│ ├── configuration.rb
│ ├── emitter.rb
│ ├── active_record_extension.rb
│ ├── container.rb
│ └── metrics
│ │ └── rack_metrics.rb
│ └── action_logger.rb
├── Gemfile
├── circle.yml
├── Rakefile
├── bin
├── setup
├── console
└── rspec
├── .codeclimate.yml
├── spec
├── rack
│ ├── action_logger_spec.rb
│ └── action_logger
│ │ ├── emit_adapter
│ │ ├── null_adapter_spec.rb
│ │ └── base_spec.rb
│ │ ├── context_spec.rb
│ │ ├── configuration_spec.rb
│ │ ├── parameter_filtering_spec.rb
│ │ ├── emitter_spec.rb
│ │ ├── active_record_extension_spec.rb
│ │ ├── metrics
│ │ └── rack_metrics_spec.rb
│ │ └── container_spec.rb
├── helper
│ └── test_application_helper.rb
└── spec_helper.rb
├── LICENSE.txt
├── .gitignore
├── rack-action_logger.gemspec
├── Gemfile.lock
├── CODE_OF_CONDUCT.md
└── README.md
/.ruby-version:
--------------------------------------------------------------------------------
1 | 2.4.1
2 |
--------------------------------------------------------------------------------
/example/rails5/lib/assets/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/example/rails5/lib/tasks/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/example/rails5/public/favicon.ico:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/example/rails5/app/assets/images/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/example/rails5/app/models/concerns/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/example/rails5/public/apple-touch-icon.png:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.rspec:
--------------------------------------------------------------------------------
1 | --format documentation
2 | --color
3 |
--------------------------------------------------------------------------------
/example/rails5/app/controllers/concerns/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/example/rails5/vendor/assets/javascripts/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/example/rails5/vendor/assets/stylesheets/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/example/rails5/app/assets/javascripts/channels/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/example/rails5/public/apple-touch-icon-precomposed.png:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/example/rails5/app/views/layouts/mailer.text.erb:
--------------------------------------------------------------------------------
1 | <%= yield %>
2 |
--------------------------------------------------------------------------------
/example/rails5/app/helpers/hello_helper.rb:
--------------------------------------------------------------------------------
1 | module HelloHelper
2 | end
3 |
--------------------------------------------------------------------------------
/example/rails5/app/helpers/application_helper.rb:
--------------------------------------------------------------------------------
1 | module ApplicationHelper
2 | end
3 |
--------------------------------------------------------------------------------
/example/rails5/app/jobs/application_job.rb:
--------------------------------------------------------------------------------
1 | class ApplicationJob < ActiveJob::Base
2 | end
3 |
--------------------------------------------------------------------------------
/example/rails5/config/initializers/fluent_logger.rb:
--------------------------------------------------------------------------------
1 | Fluent::Logger::FluentLogger.open
2 |
--------------------------------------------------------------------------------
/docs/action_log.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wapa5pow/rack-action_logger/HEAD/docs/action_log.png
--------------------------------------------------------------------------------
/docs/request_log.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wapa5pow/rack-action_logger/HEAD/docs/request_log.png
--------------------------------------------------------------------------------
/docs/sample_log.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wapa5pow/rack-action_logger/HEAD/docs/sample_log.png
--------------------------------------------------------------------------------
/example/rails5/config/routes.rb:
--------------------------------------------------------------------------------
1 | Rails.application.routes.draw do
2 | root to: 'hello#index'
3 | end
4 |
--------------------------------------------------------------------------------
/docs/attributed_log.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wapa5pow/rack-action_logger/HEAD/docs/attributed_log.png
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: false
2 | language: ruby
3 | rvm:
4 | - 2.3.1
5 | before_install: gem install bundler -v 1.13.6
6 |
--------------------------------------------------------------------------------
/lib/rack/action_logger/version.rb:
--------------------------------------------------------------------------------
1 | module Rack
2 | module ActionLogger
3 | VERSION = '0.4.0'
4 | end
5 | end
6 |
--------------------------------------------------------------------------------
/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 |
3 | # Specify your gem's dependencies in rack-action_logger.gemspec
4 | gemspec
5 |
--------------------------------------------------------------------------------
/example/rails5/public/profile.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wapa5pow/rack-action_logger/HEAD/example/rails5/public/profile.png
--------------------------------------------------------------------------------
/circle.yml:
--------------------------------------------------------------------------------
1 | deployment:
2 | codeclimate:
3 | branch: master
4 | commands:
5 | - bundle exec codeclimate-test-reporter
6 |
--------------------------------------------------------------------------------
/example/rails5/app/models/application_record.rb:
--------------------------------------------------------------------------------
1 | class ApplicationRecord < ActiveRecord::Base
2 | self.abstract_class = true
3 | end
4 |
--------------------------------------------------------------------------------
/Rakefile:
--------------------------------------------------------------------------------
1 | require "bundler/gem_tasks"
2 | require "rspec/core/rake_task"
3 |
4 | RSpec::Core::RakeTask.new(:spec)
5 |
6 | task :default => :spec
7 |
--------------------------------------------------------------------------------
/example/rails5/app/channels/application_cable/channel.rb:
--------------------------------------------------------------------------------
1 | module ApplicationCable
2 | class Channel < ActionCable::Channel::Base
3 | end
4 | end
5 |
--------------------------------------------------------------------------------
/example/rails5/app/assets/config/manifest.js:
--------------------------------------------------------------------------------
1 | //= link_tree ../images
2 | //= link_directory ../javascripts .js
3 | //= link_directory ../stylesheets .css
4 |
--------------------------------------------------------------------------------
/example/rails5/app/views/hello/index.html.erb:
--------------------------------------------------------------------------------
1 |
Hello#index
2 | Find me in app/views/hello/index.html.erb
3 |
4 |
5 |
--------------------------------------------------------------------------------
/example/rails5/app/channels/application_cable/connection.rb:
--------------------------------------------------------------------------------
1 | module ApplicationCable
2 | class Connection < ActionCable::Connection::Base
3 | end
4 | end
5 |
--------------------------------------------------------------------------------
/example/rails5/app/controllers/application_controller.rb:
--------------------------------------------------------------------------------
1 | class ApplicationController < ActionController::Base
2 | protect_from_forgery with: :exception
3 | end
4 |
--------------------------------------------------------------------------------
/example/rails5/app/mailers/application_mailer.rb:
--------------------------------------------------------------------------------
1 | class ApplicationMailer < ActionMailer::Base
2 | default from: 'from@example.com'
3 | layout 'mailer'
4 | end
5 |
--------------------------------------------------------------------------------
/example/rails5/bin/bundle:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
3 | load Gem.bin_path('bundler', 'bundle')
4 |
--------------------------------------------------------------------------------
/example/rails5/config/spring.rb:
--------------------------------------------------------------------------------
1 | %w(
2 | .ruby-version
3 | .rbenv-vars
4 | tmp/restart.txt
5 | tmp/caching-dev.txt
6 | ).each { |path| Spring.watch(path) }
7 |
--------------------------------------------------------------------------------
/bin/setup:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -euo pipefail
3 | IFS=$'\n\t'
4 | set -vx
5 |
6 | bundle install
7 |
8 | # Do any other automated setup that you need to do here
9 |
--------------------------------------------------------------------------------
/example/rails5/config/boot.rb:
--------------------------------------------------------------------------------
1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
2 |
3 | require 'bundler/setup' # Set up gems listed in the Gemfile.
4 |
--------------------------------------------------------------------------------
/.codeclimate.yml:
--------------------------------------------------------------------------------
1 | ratings:
2 | paths:
3 | - lib/**
4 | exclude_paths:
5 | - spec/**/*
6 | - docs/**/*
7 | - example/**/*
8 | - spec/**/*
9 | - "**/vendor/**/*"
10 |
--------------------------------------------------------------------------------
/example/rails5/config.ru:
--------------------------------------------------------------------------------
1 | # This file is used by Rack-based servers to start the application.
2 |
3 | require_relative 'config/environment'
4 |
5 | run Rails.application
6 |
--------------------------------------------------------------------------------
/example/rails5/bin/rails:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | APP_PATH = File.expand_path('../config/application', __dir__)
3 | require_relative '../config/boot'
4 | require 'rails/commands'
5 |
--------------------------------------------------------------------------------
/example/rails5/config/environment.rb:
--------------------------------------------------------------------------------
1 | # Load the Rails application.
2 | require_relative 'application'
3 |
4 | # Initialize the Rails application.
5 | Rails.application.initialize!
6 |
--------------------------------------------------------------------------------
/example/rails5/config/cable.yml:
--------------------------------------------------------------------------------
1 | development:
2 | adapter: async
3 |
4 | test:
5 | adapter: async
6 |
7 | production:
8 | adapter: redis
9 | url: redis://localhost:6379/1
10 |
--------------------------------------------------------------------------------
/lib/rack/action_logger/controller_concerns.rb:
--------------------------------------------------------------------------------
1 | module Rack::ActionLogger
2 | module ControllerConcerns
3 | extend ActiveSupport::Autoload
4 |
5 | autoload :RequestLog
6 | end
7 | end
8 |
9 |
--------------------------------------------------------------------------------
/example/rails5/config/initializers/session_store.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | Rails.application.config.session_store :cookie_store, key: '_rails_example_session'
4 |
--------------------------------------------------------------------------------
/spec/rack/action_logger_spec.rb:
--------------------------------------------------------------------------------
1 | require "spec_helper"
2 |
3 | describe Rack::ActionLogger do
4 | it "has a version number" do
5 | expect(Rack::ActionLogger::VERSION).not_to be nil
6 | end
7 | end
8 |
--------------------------------------------------------------------------------
/example/rails5/config/initializers/mime_types.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Add new mime types for use in respond_to blocks:
4 | # Mime::Type.register "text/richtext", :rtf
5 |
--------------------------------------------------------------------------------
/lib/rack/action_logger/emit_adapter/null_adapter.rb:
--------------------------------------------------------------------------------
1 | require 'rack/action_logger/emit_adapter/base'
2 |
3 | module Rack::ActionLogger::EmitAdapter
4 | class NullAdapter < Base
5 | # Emit nothing
6 | end
7 | end
8 |
--------------------------------------------------------------------------------
/lib/rack/action_logger/metrics.rb:
--------------------------------------------------------------------------------
1 | require 'active_support'
2 |
3 | module Rack::ActionLogger
4 | module Metrics
5 | extend ActiveSupport::Autoload
6 |
7 | autoload :RackMetrics
8 | end
9 | end
10 |
11 |
--------------------------------------------------------------------------------
/example/rails5/app/assets/stylesheets/hello.scss:
--------------------------------------------------------------------------------
1 | // Place all the styles related to the hello controller here.
2 | // They will automatically be included in application.css.
3 | // You can use Sass (SCSS) here: http://sass-lang.com/
4 |
--------------------------------------------------------------------------------
/example/rails5/config/initializers/application_controller_renderer.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # ApplicationController.renderer.defaults.merge!(
4 | # http_host: 'example.org',
5 | # https: false
6 | # )
7 |
--------------------------------------------------------------------------------
/example/rails5/public/robots.txt:
--------------------------------------------------------------------------------
1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file
2 | #
3 | # To ban all spiders from the entire site uncomment the next two lines:
4 | # User-agent: *
5 | # Disallow: /
6 |
--------------------------------------------------------------------------------
/example/rails5/app/assets/javascripts/hello.coffee:
--------------------------------------------------------------------------------
1 | # Place all the behaviors and hooks related to the matching controller here.
2 | # All this logic will automatically be available in application.js.
3 | # You can use CoffeeScript in this file: http://coffeescript.org/
4 |
--------------------------------------------------------------------------------
/example/rails5/config/initializers/filter_parameter_logging.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Configure sensitive parameters which will be filtered from the log file.
4 | Rails.application.config.filter_parameters += [:password]
5 |
--------------------------------------------------------------------------------
/example/rails5/Rakefile:
--------------------------------------------------------------------------------
1 | # Add your own tasks in files placed in lib/tasks ending in .rake,
2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
3 |
4 | require_relative 'config/application'
5 |
6 | Rails.application.load_tasks
7 |
--------------------------------------------------------------------------------
/lib/rack/action_logger/emit_adapter.rb:
--------------------------------------------------------------------------------
1 | require 'active_support'
2 |
3 | module Rack::ActionLogger
4 | module EmitAdapter
5 | extend ActiveSupport::Autoload
6 |
7 | autoload :FluentAdapter
8 | autoload :LoggerAdapter
9 | autoload :NullAdapter
10 | end
11 | end
12 |
13 |
--------------------------------------------------------------------------------
/example/rails5/config/initializers/cookies_serializer.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Specify a serializer for the signed and encrypted cookie jars.
4 | # Valid options are :json, :marshal, and :hybrid.
5 | Rails.application.config.action_dispatch.cookies_serializer = :json
6 |
--------------------------------------------------------------------------------
/example/rails5/spec/controllers/hello_controller_spec.rb:
--------------------------------------------------------------------------------
1 | require 'rails_helper'
2 |
3 | RSpec.describe HelloController, type: :controller do
4 | describe 'GET #index' do
5 | it 'returns http success' do
6 | get :index
7 | expect(response).to have_http_status(:success)
8 | end
9 | end
10 | end
11 |
--------------------------------------------------------------------------------
/example/rails5/app/views/layouts/mailer.html.erb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
8 |
9 |
10 |
11 | <%= yield %>
12 |
13 |
14 |
--------------------------------------------------------------------------------
/example/rails5/app/controllers/hello_controller.rb:
--------------------------------------------------------------------------------
1 | class HelloController < ApplicationController
2 | def index
3 | Rack::ActionLogger::Container.merge_attributes({ user_id: 123 })
4 | Rack::ActionLogger::Container.add_append_log({value: 'with_tag' }, 'activities')
5 | Rack::ActionLogger::Container.add_append_log({value: 'no_tag' }, nil)
6 | end
7 | end
8 |
--------------------------------------------------------------------------------
/example/rails5/.rakeTasks:
--------------------------------------------------------------------------------
1 |
2 |
8 |
--------------------------------------------------------------------------------
/example/rails5/config/application.rb:
--------------------------------------------------------------------------------
1 | require_relative 'boot'
2 |
3 | require 'rails/all'
4 |
5 | # Require the gems listed in Gemfile, including any gems
6 | # you've limited to :test, :development, or :production.
7 | Bundler.require(*Rails.groups)
8 |
9 | module RailsExample
10 | class Application < Rails::Application
11 | config.middleware.use Rack::ActionLogger
12 | end
13 | end
14 |
--------------------------------------------------------------------------------
/lib/rack/action_logger/emit_adapter/fluent_adapter.rb:
--------------------------------------------------------------------------------
1 | require 'rack/action_logger/emit_adapter/base'
2 |
3 | module Rack::ActionLogger::EmitAdapter
4 | class FluentAdapter < Base
5 | def self.emit(hash)
6 | tag = hash[:tag] ? hash[:tag] : Rack::ActionLogger.configuration.default_tag
7 | hash = wrap(hash)
8 | Fluent::Logger.post(tag, hash)
9 | end
10 | end
11 | end
12 |
--------------------------------------------------------------------------------
/bin/console:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 |
3 | require "bundler/setup"
4 | require "rack/action_logger"
5 |
6 | # You can add fixtures and/or initialization code here to make experimenting
7 | # with your gem easier. You can also use a different console, if you like.
8 |
9 | # (If you use this, don't forget to add pry to your Gemfile!)
10 | # require "pry"
11 | # Pry.start
12 |
13 | require "irb"
14 | IRB.start
15 |
--------------------------------------------------------------------------------
/example/rails5/db/seeds.rb:
--------------------------------------------------------------------------------
1 | # This file should contain all the record creation needed to seed the database with its default values.
2 | # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
3 | #
4 | # Examples:
5 | #
6 | # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
7 | # Character.create(name: 'Luke', movie: movies.first)
8 |
--------------------------------------------------------------------------------
/example/rails5/config/initializers/rack-action_logger.rb:
--------------------------------------------------------------------------------
1 | Rack::ActionLogger.configure do |config|
2 | # config.emit_adapter = Rack::ActionLogger::EmitAdapter::FluentAdapter
3 | config.emit_adapter = Rack::ActionLogger::EmitAdapter::LoggerAdapter
4 | config.wrap_key = :message
5 | config.logger = Rails.logger
6 | config.filters = Rails.application.config.filter_parameters
7 | config.rack_request_blacklist = []
8 | end
9 |
--------------------------------------------------------------------------------
/spec/rack/action_logger/emit_adapter/null_adapter_spec.rb:
--------------------------------------------------------------------------------
1 | require 'spec_helper'
2 | require 'rack/action_logger/emit_adapter/null_adapter'
3 |
4 | RSpec.describe Rack::ActionLogger::EmitAdapter::NullAdapter do
5 | let(:hash) { { key: 'value' } }
6 |
7 | describe 'emit' do
8 | it 'should emit nothing' do
9 | expect(described_class.emit(hash)).not_to eq raise_error
10 | end
11 |
12 | end
13 | end
14 |
--------------------------------------------------------------------------------
/example/rails5/app/views/layouts/application.html.erb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | RailsExample
5 | <%= csrf_meta_tags %>
6 |
7 | <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
8 | <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
9 |
10 |
11 |
12 | <%= yield %>
13 |
14 |
15 |
--------------------------------------------------------------------------------
/example/rails5/app/assets/javascripts/cable.js:
--------------------------------------------------------------------------------
1 | // Action Cable provides the framework to deal with WebSockets in Rails.
2 | // You can generate new channels where WebSocket features live using the rails generate channel command.
3 | //
4 | //= require action_cable
5 | //= require_self
6 | //= require_tree ./channels
7 |
8 | (function() {
9 | this.App || (this.App = {});
10 |
11 | App.cable = ActionCable.createConsumer();
12 |
13 | }).call(this);
14 |
--------------------------------------------------------------------------------
/lib/rack/action_logger/emit_adapter/base.rb:
--------------------------------------------------------------------------------
1 | require 'rack/action_logger'
2 |
3 | module Rack::ActionLogger::EmitAdapter
4 | class Base
5 | def self.emit(hash); end
6 |
7 | def self.wrap(hash)
8 | result = {}
9 | wrap_key = Rack::ActionLogger.configuration.wrap_key
10 | if wrap_key
11 | result[wrap_key] = hash
12 | else
13 | result = hash
14 | end
15 | result
16 | end
17 | end
18 | end
19 |
--------------------------------------------------------------------------------
/example/rails5/config/initializers/backtrace_silencers.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
5 |
6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
7 | # Rails.backtrace_cleaner.remove_silencers!
8 |
--------------------------------------------------------------------------------
/bin/rspec:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | # frozen_string_literal: true
3 | #
4 | # This file was generated by Bundler.
5 | #
6 | # The application 'rspec' is installed as part of a gem, and
7 | # this file is here to facilitate running it.
8 | #
9 |
10 | require "pathname"
11 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
12 | Pathname.new(__FILE__).realpath)
13 |
14 | require "rubygems"
15 | require "bundler/setup"
16 |
17 | load Gem.bin_path("rspec-core", "rspec")
18 |
--------------------------------------------------------------------------------
/example/rails5/bin/rake:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | # frozen_string_literal: true
3 | #
4 | # This file was generated by Bundler.
5 | #
6 | # The application 'rake' is installed as part of a gem, and
7 | # this file is here to facilitate running it.
8 | #
9 |
10 | require "pathname"
11 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
12 | Pathname.new(__FILE__).realpath)
13 |
14 | require "rubygems"
15 | require "bundler/setup"
16 |
17 | load Gem.bin_path("rake", "rake")
18 |
--------------------------------------------------------------------------------
/example/rails5/bin/rspec:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | # frozen_string_literal: true
3 | #
4 | # This file was generated by Bundler.
5 | #
6 | # The application 'rspec' is installed as part of a gem, and
7 | # this file is here to facilitate running it.
8 | #
9 |
10 | require "pathname"
11 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
12 | Pathname.new(__FILE__).realpath)
13 |
14 | require "rubygems"
15 | require "bundler/setup"
16 |
17 | load Gem.bin_path("rspec-core", "rspec")
18 |
--------------------------------------------------------------------------------
/lib/rack/action_logger/emit_adapter/logger_adapter.rb:
--------------------------------------------------------------------------------
1 | require 'json'
2 | require 'rack/action_logger/emit_adapter/base'
3 |
4 | module Rack::ActionLogger::EmitAdapter
5 | class LoggerAdapter < Base
6 | def self.emit(hash)
7 | hash = wrap(hash)
8 | if Rack::ActionLogger.configuration.pretty_print
9 | Rack::ActionLogger.logger.info(JSON.pretty_generate(hash))
10 | else
11 | Rack::ActionLogger.logger.info(hash)
12 | end
13 | end
14 | end
15 | end
16 |
--------------------------------------------------------------------------------
/example/rails5/README.md:
--------------------------------------------------------------------------------
1 | # README
2 |
3 | This README would normally document whatever steps are necessary to get the
4 | application up and running.
5 |
6 | Things you may want to cover:
7 |
8 | * Ruby version
9 |
10 | * System dependencies
11 |
12 | * Configuration
13 |
14 | * Database creation
15 |
16 | * Database initialization
17 |
18 | * How to run the test suite
19 |
20 | * Services (job queues, cache servers, search engines, etc.)
21 |
22 | * Deployment instructions
23 |
24 | * ...
25 |
--------------------------------------------------------------------------------
/spec/rack/action_logger/context_spec.rb:
--------------------------------------------------------------------------------
1 | require "spec_helper"
2 | require 'rack/test'
3 |
4 | RSpec.describe Rack::ActionLogger::Context do
5 | include TestApplicationHelper
6 | include Rack::Test::Methods
7 |
8 | let(:test_app) { TestApplicationHelper::TestApplication.new }
9 | let(:app) { described_class.new(test_app) }
10 |
11 | describe "GET '/hoge'" do
12 | it 'should return 200 OK' do
13 | get '/hoge'
14 | expect(last_response.status).to eq 200
15 | end
16 | end
17 |
18 | end
19 |
--------------------------------------------------------------------------------
/example/rails5/config/initializers/assets.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Version of your assets, change this if you want to expire all your assets.
4 | Rails.application.config.assets.version = '1.0'
5 |
6 | # Add additional assets to the asset load path
7 | # Rails.application.config.assets.paths << Emoji.images_path
8 |
9 | # Precompile additional assets.
10 | # application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
11 | # Rails.application.config.assets.precompile += %w( search.js )
12 |
--------------------------------------------------------------------------------
/spec/helper/test_application_helper.rb:
--------------------------------------------------------------------------------
1 | module TestApplicationHelper
2 | extend self
3 |
4 | class TestApplication
5 | def call(env)
6 | code = 200
7 | body = [ "test body" ]
8 | header = { "Content-Type" => "text/html;charset=utf-8",
9 | "Content-Length" => "9",
10 | "X-XSS-Protection" => "1; mode=block",
11 | "X-Content-Type-Options" => "nosniff",
12 | "X-Frame-Options" => "SAMEORIGIN" }
13 | [ code, header, body ]
14 | end
15 | end
16 | end
17 |
--------------------------------------------------------------------------------
/example/rails5/config/initializers/wrap_parameters.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # This file contains settings for ActionController::ParamsWrapper which
4 | # is enabled by default.
5 |
6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
7 | ActiveSupport.on_load(:action_controller) do
8 | wrap_parameters format: [:json]
9 | end
10 |
11 | # To enable root element in JSON for ActiveRecord objects.
12 | # ActiveSupport.on_load(:active_record) do
13 | # self.include_root_in_json = true
14 | # end
15 |
--------------------------------------------------------------------------------
/example/rails5/config/database.yml:
--------------------------------------------------------------------------------
1 | # SQLite version 3.x
2 | # gem install sqlite3
3 | #
4 | # Ensure the SQLite 3 gem is defined in your Gemfile
5 | # gem 'sqlite3'
6 | #
7 | default: &default
8 | adapter: sqlite3
9 | pool: 5
10 | timeout: 5000
11 |
12 | development:
13 | <<: *default
14 | database: db/development.sqlite3
15 |
16 | # Warning: The database defined as "test" will be erased and
17 | # re-generated from your development database when you run "rake".
18 | # Do not set this db to the same as development or production.
19 | test:
20 | <<: *default
21 | database: db/test.sqlite3
22 |
23 | production:
24 | <<: *default
25 | database: db/production.sqlite3
26 |
--------------------------------------------------------------------------------
/spec/spec_helper.rb:
--------------------------------------------------------------------------------
1 | require 'rspec'
2 | require 'simplecov'
3 | require 'codeclimate-test-reporter'
4 |
5 | dir = File.join('coverage')
6 | SimpleCov.coverage_dir(dir)
7 |
8 | SimpleCov.start do
9 | add_filter '/vendor/'
10 | add_filter '/spec/'
11 | add_filter '/example/'
12 | add_filter '/docs/'
13 |
14 | add_group 'lib', 'lib'
15 | end
16 |
17 | require 'rack/action_logger'
18 | require 'rack/action_logger/emit_adapter/null_adapter'
19 | require 'helper/test_application_helper'
20 |
21 | Rack::ActionLogger.configure do |config|
22 | config.emit_adapter = Rack::ActionLogger::EmitAdapter::NullAdapter
23 | config.wrap_key = nil
24 | config.logger = Logger.new(nil)
25 | end
26 |
--------------------------------------------------------------------------------
/spec/rack/action_logger/emit_adapter/base_spec.rb:
--------------------------------------------------------------------------------
1 | require "spec_helper"
2 | require 'rack/action_logger/emit_adapter/base'
3 |
4 | RSpec.describe Rack::ActionLogger::EmitAdapter::Base do
5 | let(:hash) { { key: 'value' } }
6 |
7 | describe 'wrap' do
8 | it 'should work without key' do
9 | Rack::ActionLogger.configure do |config|
10 | config.wrap_key = nil
11 | end
12 | expect(described_class.wrap(hash)).to eq hash
13 | end
14 |
15 | it 'should work with key' do
16 | Rack::ActionLogger.configure do |config|
17 | config.wrap_key = :message
18 | end
19 | expected = { message: hash }
20 | expect(described_class.wrap(hash)).to eq expected
21 | end
22 | end
23 | end
24 |
--------------------------------------------------------------------------------
/example/rails5/config/initializers/inflections.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Add new inflection rules using the following format. Inflections
4 | # are locale specific, and you may define rules for as many different
5 | # locales as you wish. All of these examples are active by default:
6 | # ActiveSupport::Inflector.inflections(:en) do |inflect|
7 | # inflect.plural /^(ox)$/i, '\1en'
8 | # inflect.singular /^(ox)en/i, '\1'
9 | # inflect.irregular 'person', 'people'
10 | # inflect.uncountable %w( fish sheep )
11 | # end
12 |
13 | # These inflection rules are supported but not enabled by default:
14 | # ActiveSupport::Inflector.inflections(:en) do |inflect|
15 | # inflect.acronym 'RESTful'
16 | # end
17 |
--------------------------------------------------------------------------------
/example/rails5/config/locales/en.yml:
--------------------------------------------------------------------------------
1 | # Files in the config/locales directory are used for internationalization
2 | # and are automatically loaded by Rails. If you want to use locales other
3 | # than English, add the necessary files in this directory.
4 | #
5 | # To use the locales, use `I18n.t`:
6 | #
7 | # I18n.t 'hello'
8 | #
9 | # In views, this is aliased to just `t`:
10 | #
11 | # <%= t('hello') %>
12 | #
13 | # To use a different locale, set it with `I18n.locale`:
14 | #
15 | # I18n.locale = :es
16 | #
17 | # This would use the information in config/locales/es.yml.
18 | #
19 | # To learn more, please read the Rails Internationalization guide
20 | # available at http://guides.rubyonrails.org/i18n.html.
21 |
22 | en:
23 | hello: "Hello world"
24 |
--------------------------------------------------------------------------------
/example/rails5/app/assets/stylesheets/application.css:
--------------------------------------------------------------------------------
1 | /*
2 | * This is a manifest file that'll be compiled into application.css, which will include all the files
3 | * listed below.
4 | *
5 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
6 | * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
7 | *
8 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the
9 | * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
10 | * files in this directory. Styles in this file should be added after the last require_* statement.
11 | * It is generally better to create a new file per style scope.
12 | *
13 | *= require_tree .
14 | *= require_self
15 | */
16 |
--------------------------------------------------------------------------------
/lib/rack/action_logger/context.rb:
--------------------------------------------------------------------------------
1 | module Rack::ActionLogger
2 | class Context
3 |
4 | def initialize(app)
5 | @app = app
6 | end
7 |
8 | def call(env)
9 | Emitter.new.emit do
10 | status_code, headers, body = @app.call(env)
11 | capture_rack_log(env, status_code, headers, body)
12 | [status_code, headers, body]
13 | end
14 | end
15 |
16 | def capture_rack_log(env, status_code, headers, body)
17 | rack_metrics = Rack::ActionLogger.configuration.rack_metrics.new(env, status_code, headers, body)
18 | return if rack_metrics.metrics.nil?
19 | Rack::ActionLogger::Container.set_request_log(rack_metrics.metrics, rack_metrics.tag_suffix)
20 | Rack::ActionLogger::Container.merge_attributes({ request_id: rack_metrics.request_id })
21 | end
22 |
23 | end
24 | end
25 |
--------------------------------------------------------------------------------
/example/rails5/app/assets/javascripts/application.js:
--------------------------------------------------------------------------------
1 | // This is a manifest file that'll be compiled into application.js, which will include all the files
2 | // listed below.
3 | //
4 | // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
5 | // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
6 | //
7 | // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
8 | // compiled file. JavaScript code in this file should be added after the last require_* statement.
9 | //
10 | // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
11 | // about supported directives.
12 | //
13 | //= require jquery
14 | //= require jquery_ujs
15 | //= require turbolinks
16 | //= require_tree .
17 |
--------------------------------------------------------------------------------
/example/rails5/db/schema.rb:
--------------------------------------------------------------------------------
1 | # This file is auto-generated from the current state of the database. Instead
2 | # of editing this file, please use the migrations feature of Active Record to
3 | # incrementally modify your database, and then regenerate this schema definition.
4 | #
5 | # Note that this schema.rb definition is the authoritative source for your
6 | # database schema. If you need to create the application database on another
7 | # system, you should be using db:schema:load, not running all the migrations
8 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations
9 | # you'll amass, the slower it'll run and the greater likelihood for issues).
10 | #
11 | # It's strongly recommended that you check this file into your version control system.
12 |
13 | ActiveRecord::Schema.define(version: 0) do
14 |
15 | end
16 |
--------------------------------------------------------------------------------
/example/rails5/bin/update:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require 'pathname'
3 | require 'fileutils'
4 | include FileUtils
5 |
6 | # path to your application root.
7 | APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
8 |
9 | def system!(*args)
10 | system(*args) || abort("\n== Command #{args} failed ==")
11 | end
12 |
13 | chdir APP_ROOT do
14 | # This script is a way to update your development environment automatically.
15 | # Add necessary update steps to this file.
16 |
17 | puts '== Installing dependencies =='
18 | system! 'gem install bundler --conservative'
19 | system('bundle check') || system!('bundle install')
20 |
21 | puts "\n== Updating database =="
22 | system! 'bin/rails db:migrate'
23 |
24 | puts "\n== Removing old logs and tempfiles =="
25 | system! 'bin/rails log:clear tmp:clear'
26 |
27 | puts "\n== Restarting application server =="
28 | system! 'bin/rails restart'
29 | end
30 |
--------------------------------------------------------------------------------
/lib/rack/action_logger.rb:
--------------------------------------------------------------------------------
1 | module Rack::ActionLogger
2 | class << self
3 | attr_accessor :configuration
4 | end
5 |
6 | def self.new(app)
7 | Context.new(app)
8 | end
9 |
10 | def self.configure
11 | yield configuration
12 | end
13 |
14 | def self.configuration
15 | @configuration ||= Configuration.new
16 | end
17 |
18 | def self.logger
19 | configuration.logger
20 | end
21 |
22 | autoload :Configuration, 'rack/action_logger/configuration'
23 | autoload :Container, 'rack/action_logger/container'
24 | autoload :Context, 'rack/action_logger/context'
25 | autoload :Emitter, 'rack/action_logger/emitter'
26 | autoload :ControllerConcerns, 'rack/action_logger/controller_concerns'
27 | autoload :EmitAdapter, 'rack/action_logger/emit_adapter'
28 | autoload :ParameterFiltering, 'rack/action_logger/parameter_filtering'
29 | autoload :Metrics, 'rack/action_logger/metrics'
30 | autoload :ActiveRecordExtension, 'rack/action_logger/active_record_extension'
31 | end
32 |
--------------------------------------------------------------------------------
/example/rails5/config/secrets.yml:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Your secret key is used for verifying the integrity of signed cookies.
4 | # If you change this key, all old signed cookies will become invalid!
5 |
6 | # Make sure the secret is at least 30 characters and all random,
7 | # no regular words or you'll be exposed to dictionary attacks.
8 | # You can use `rails secret` to generate a secure secret key.
9 |
10 | # Make sure the secrets in this file are kept private
11 | # if you're sharing your code publicly.
12 |
13 | development:
14 | secret_key_base: acdae7cecc44715a50ad07d3b639e68a23d10864bfdd5b91b20dade7ef14d3bedecf87fa33f0bf8e650f7f6c7c85a8328c419e33504d507fac4728e3ce96b800
15 |
16 | test:
17 | secret_key_base: 8762de063618668bbf695c8fee7a9d0ea61b20ce3f03ad620e083767f0d872e4271e74aaa108e8e737c96dd9d4604a22b7b15a519834b93b91da391cc080c701
18 |
19 | # Do not keep production secrets in the repository,
20 | # instead read values from the environment.
21 | production:
22 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
23 |
--------------------------------------------------------------------------------
/example/rails5/bin/setup:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require 'pathname'
3 | require 'fileutils'
4 | include FileUtils
5 |
6 | # path to your application root.
7 | APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
8 |
9 | def system!(*args)
10 | system(*args) || abort("\n== Command #{args} failed ==")
11 | end
12 |
13 | chdir APP_ROOT do
14 | # This script is a starting point to setup your application.
15 | # Add necessary setup steps to this file.
16 |
17 | puts '== Installing dependencies =='
18 | system! 'gem install bundler --conservative'
19 | system('bundle check') || system!('bundle install')
20 |
21 | # puts "\n== Copying sample files =="
22 | # unless File.exist?('config/database.yml')
23 | # cp 'config/database.yml.sample', 'config/database.yml'
24 | # end
25 |
26 | puts "\n== Preparing database =="
27 | system! 'bin/rails db:setup'
28 |
29 | puts "\n== Removing old logs and tempfiles =="
30 | system! 'bin/rails log:clear tmp:clear'
31 |
32 | puts "\n== Restarting application server =="
33 | system! 'bin/rails restart'
34 | end
35 |
--------------------------------------------------------------------------------
/spec/rack/action_logger/configuration_spec.rb:
--------------------------------------------------------------------------------
1 | require "spec_helper"
2 |
3 | RSpec.describe Rack::ActionLogger::Configuration do
4 | describe 'tag_prefix' do
5 | it 'should be default tag prefix if nil' do
6 | Rack::ActionLogger.configure { |c| c.tag_prefix = nil }
7 | expect(Rack::ActionLogger.configuration.tag_prefix).to eq described_class::DEFAULT_TAG_PREFIX
8 | end
9 |
10 | it 'should be default tag prefix if empty' do
11 | Rack::ActionLogger.configure { |c| c.tag_prefix = '' }
12 | expect(Rack::ActionLogger.configuration.tag_prefix).to eq described_class::DEFAULT_TAG_PREFIX
13 | end
14 |
15 | it 'should be the tag' do
16 | Rack::ActionLogger.configure { |c| c.tag_prefix = 'tag' }
17 | expect(Rack::ActionLogger.configuration.tag_prefix).to eq 'tag'
18 | end
19 | end
20 |
21 | describe 'default_tag' do
22 | it 'should be the tag' do
23 | Rack::ActionLogger.configure { |c| c.tag_prefix = 'tag' }
24 | expect(Rack::ActionLogger.configuration.default_tag).to eq 'tag.log'
25 | end
26 | end
27 | end
28 |
--------------------------------------------------------------------------------
/lib/rack/action_logger/parameter_filtering.rb:
--------------------------------------------------------------------------------
1 | module Rack::ActionLogger
2 | module ParameterFiltering
3 | FILTERED = '[FILTERED]'.freeze # :nodoc:
4 |
5 | class << self
6 |
7 | def apply_filter(original_params)
8 | filtered_params = {}
9 |
10 | original_params.each do |key, value|
11 | if compiled_filters.any? { |r| key =~ r }
12 | value = FILTERED
13 | elsif value.is_a?(Hash)
14 | value = apply_filter(value)
15 | elsif value.is_a?(Array)
16 | value = value.map { |v| v.is_a?(Hash) ? apply_filter(v) : v }
17 | end
18 |
19 | filtered_params[key] = value
20 | end
21 |
22 | filtered_params
23 | end
24 |
25 | private
26 |
27 | def compiled_filters
28 | @compiled_filters ||= compile(Rack::ActionLogger.configuration.filters)
29 | end
30 |
31 | def compile(filters)
32 | filter_strings = filters.map(&:to_s)
33 | filter_strings.map { |item| Regexp.compile(Regexp.escape(item)) }
34 | end
35 |
36 | end
37 | end
38 | end
39 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 Koichi Ishida
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
22 |
--------------------------------------------------------------------------------
/example/rails5/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.gitignore.io/api/rails
3 |
4 | ### Rails ###
5 | *.rbc
6 | capybara-*.html
7 | .rspec
8 | /log
9 | /tmp
10 | /db/*.sqlite3
11 | /db/*.sqlite3-journal
12 | /public/system
13 | /coverage/
14 | /spec/tmp
15 | **.orig
16 | rerun.txt
17 | pickle-email-*.html
18 |
19 | # TODO Comment out this rule if you are OK with secrets being uploaded to the repo
20 | config/initializers/secret_token.rb
21 |
22 | # Only include if you have production secrets in this file, which is no longer a Rails default
23 | # config/secrets.yml
24 |
25 | # dotenv
26 | # TODO Comment out this rule if environment variables can be committed
27 | .env
28 |
29 | ## Environment normalization:
30 | /.bundle
31 | /vendor/bundle
32 |
33 | # these should all be checked in to normalize the environment:
34 | # Gemfile.lock, .ruby-version, .ruby-gemset
35 |
36 | # unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
37 | .rvmrc
38 |
39 | # if using bower-rails ignore default bower_components path bower.json files
40 | /vendor/assets/bower_components
41 | *.bowerrc
42 | bower.json
43 |
44 | # Ignore pow environment settings
45 | .powenv
46 |
47 | # Ignore Byebug command history file.
48 | .byebug_history
49 |
--------------------------------------------------------------------------------
/example/rails5/config/initializers/new_framework_defaults.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 | #
3 | # This file contains migration options to ease your Rails 5.0 upgrade.
4 | #
5 | # Read the Rails 5.0 release notes for more info on each option.
6 |
7 | # Enable per-form CSRF tokens. Previous versions had false.
8 | Rails.application.config.action_controller.per_form_csrf_tokens = true
9 |
10 | # Enable origin-checking CSRF mitigation. Previous versions had false.
11 | Rails.application.config.action_controller.forgery_protection_origin_check = true
12 |
13 | # Make Ruby 2.4 preserve the timezone of the receiver when calling `to_time`.
14 | # Previous versions had false.
15 | ActiveSupport.to_time_preserves_timezone = true
16 |
17 | # Require `belongs_to` associations by default. Previous versions had false.
18 | Rails.application.config.active_record.belongs_to_required_by_default = true
19 |
20 | # Do not halt callback chains when a callback returns false. Previous versions had true.
21 | ActiveSupport.halt_callback_chains_on_return_false = false
22 |
23 | # Configure SSL options to enable HSTS with subdomains. Previous versions had false.
24 | Rails.application.config.ssl_options = { hsts: { subdomains: true } }
25 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.gitignore.io/api/ruby
3 |
4 | ### Ruby ###
5 | *.rbc
6 | /.config
7 | /coverage/
8 | /InstalledFiles
9 | /pkg/
10 | /spec/reports/
11 | /spec/examples.txt
12 | /test/tmp/
13 | /test/version_tmp/
14 | /tmp/
15 |
16 | # Used by dotenv library to load environment variables.
17 | # .env
18 |
19 | ## Specific to RubyMotion:
20 | .dat*
21 | .repl_history
22 | build/
23 | *.bridgesupport
24 | build-iPhoneOS/
25 | build-iPhoneSimulator/
26 |
27 | ## Specific to RubyMotion (use of CocoaPods):
28 | #
29 | # We recommend against adding the Pods directory to your .gitignore. However
30 | # you should judge for yourself, the pros and cons are mentioned at:
31 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
32 | #
33 | # vendor/Pods/
34 |
35 | ## Documentation cache and generated files:
36 | /.yardoc/
37 | /_yardoc/
38 | /doc/
39 | /rdoc/
40 |
41 | ## Environment normalization:
42 | /.bundle/
43 | /vendor/bundle
44 | /lib/bundler/man/
45 |
46 | # for a library or gem, you might want to ignore these files since the code is
47 | # intended to run in multiple environments; otherwise, check them in:
48 | # Gemfile.lock
49 | # .ruby-version
50 | # .ruby-gemset
51 |
52 | # unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
53 | .rvmrc
54 |
55 | .generators
56 |
57 |
--------------------------------------------------------------------------------
/lib/rack/action_logger/configuration.rb:
--------------------------------------------------------------------------------
1 | require 'rack/action_logger/emit_adapter/logger_adapter'
2 | require 'rack/action_logger/emit_adapter/fluent_adapter'
3 | require 'rack/action_logger/emit_adapter/null_adapter'
4 | require 'logger'
5 |
6 | module Rack::ActionLogger
7 | class Configuration
8 | DEFAULT_TAG_PREFIX = 'action'
9 |
10 | attr_accessor :emit_adapter
11 | attr_accessor :wrap_key
12 | attr_accessor :tag_prefix
13 | attr_accessor :logger
14 | attr_accessor :filters
15 | attr_accessor :rack_request_blacklist
16 | attr_accessor :pretty_print
17 | attr_accessor :rack_metrics
18 | attr_accessor :rack_content_types
19 | attr_accessor :rack_unified_tag
20 |
21 | def initialize
22 | @emit_adapter = EmitAdapter::LoggerAdapter
23 | @tag_prefix = DEFAULT_TAG_PREFIX
24 | @logger = Logger.new(STDOUT)
25 | @logger.progname = 'rack-action_logger'
26 | @filters = ['password']
27 | @rack_request_blacklist = [:request_headers, :response_headers, :response_json_body]
28 | @pretty_print = true
29 | @rack_metrics = Rack::ActionLogger::Metrics::RackMetrics
30 | @rack_content_types = %w(text/html application/json)
31 | @rack_unified_tag = true
32 | end
33 |
34 | def tag_prefix
35 | if @tag_prefix.to_s.empty?
36 | Rack::ActionLogger.logger.error('tag_prefix should not be empty')
37 | @tag_prefix = DEFAULT_TAG_PREFIX
38 | end
39 | @tag_prefix
40 | end
41 |
42 | def default_tag
43 | [tag_prefix, 'log'].join('.')
44 | end
45 | end
46 | end
47 |
--------------------------------------------------------------------------------
/rack-action_logger.gemspec:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | lib = File.expand_path('../lib', __FILE__)
3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4 | require 'rack/action_logger/version'
5 |
6 | Gem::Specification.new do |spec|
7 | spec.name = 'rack-action_logger'
8 | spec.version = Rack::ActionLogger::VERSION
9 | spec.required_ruby_version = '>= 2.0.0'
10 | spec.required_rubygems_version = '>= 1.3.5'
11 | spec.rubygems_version = Gem::VERSION
12 | spec.authors = ['Koichi Ishida']
13 | spec.email = ['wapa5pow@gmail.com']
14 | spec.date = Time.now.strftime('%Y-%m-%d')
15 | spec.summary = 'Rack::ActionLogger is a tool to log user activity'
16 | spec.description = 'Rack::ActionLogger is a tool to log user activity'
17 | spec.homepage = 'https://github.com/wapa5pow/rack-action_logger'
18 | spec.license = 'MIT'
19 |
20 | spec.files = `git ls-files -z`.split("\x0").reject do |f|
21 | f.match(%r{^(test|spec|features|docs|example)/})
22 | end
23 | spec.bindir = 'exe'
24 | spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
25 | spec.require_paths = ['lib']
26 |
27 | spec.add_dependency 'activesupport'
28 | spec.add_dependency 'fluent-logger', '~> 0.5'
29 | spec.add_dependency 'woothee', '~> 1.4'
30 |
31 | spec.add_development_dependency 'bundler', '~> 1.13'
32 | spec.add_development_dependency 'rake', '~> 10.0'
33 | spec.add_development_dependency 'rspec', '~> 3.0'
34 | spec.add_development_dependency 'rack-test', '~> 0.6.3'
35 | spec.add_development_dependency 'simplecov'
36 | spec.add_development_dependency 'codeclimate-test-reporter'
37 | end
38 |
--------------------------------------------------------------------------------
/lib/rack/action_logger/emitter.rb:
--------------------------------------------------------------------------------
1 | module Rack::ActionLogger
2 | class Emitter
3 |
4 | def initialize
5 | @can_emit = !Container.is_emit_started
6 | unless @can_emit
7 | Rack::ActionLogger.logger.error("#{self.class} is already defined.")
8 | Rack::ActionLogger.logger.error("#{Thread.current.backtrace.join("\n")}")
9 | end
10 | @emit_adapter = Rack::ActionLogger.configuration.emit_adapter
11 | @container = Container
12 | end
13 |
14 | def emit(context=nil)
15 | @container.is_emit_started = true
16 | @container.import(context) if context
17 | result = yield
18 | emit_all_logs # emit log unless exception raised
19 | result
20 | ensure
21 | @container.clear if @can_emit
22 | end
23 |
24 | private
25 |
26 | def emit_all_logs
27 | return unless @can_emit
28 | emit_request_log
29 | emit_append_logs
30 | end
31 |
32 | def emit_request_log
33 | return unless (@container.request_log.is_a?(Hash) && @container.request_log != {})
34 | hash = @container.request_log.merge @container.attributes
35 | hash = format_tag(hash)
36 | @emit_adapter.emit(hash)
37 | end
38 |
39 | def emit_append_logs
40 | @container.append_logs.each do |hash|
41 | hash = format_tag(hash)
42 | @emit_adapter.emit(@container.attributes.merge(hash))
43 | end
44 | end
45 |
46 | def format_tag(hash)
47 | if hash[:tag]
48 | hash[:tag] = [Rack::ActionLogger.configuration.tag_prefix, hash[:tag]].join('.')
49 | else
50 | hash[:tag] = Rack::ActionLogger.configuration.default_tag
51 | end
52 | hash
53 | end
54 | end
55 | end
56 |
--------------------------------------------------------------------------------
/Gemfile.lock:
--------------------------------------------------------------------------------
1 | PATH
2 | remote: .
3 | specs:
4 | rack-action_logger (0.4.0)
5 | activesupport
6 | fluent-logger (~> 0.5)
7 | woothee (~> 1.4)
8 |
9 | GEM
10 | remote: https://rubygems.org/
11 | specs:
12 | activesupport (5.0.0.1)
13 | concurrent-ruby (~> 1.0, >= 1.0.2)
14 | i18n (~> 0.7)
15 | minitest (~> 5.1)
16 | tzinfo (~> 1.1)
17 | codeclimate-test-reporter (1.0.3)
18 | simplecov
19 | concurrent-ruby (1.0.2)
20 | diff-lcs (1.2.5)
21 | docile (1.1.5)
22 | fluent-logger (0.6.1)
23 | msgpack (>= 0.5.6, < 2)
24 | i18n (0.7.0)
25 | json (2.0.2)
26 | minitest (5.9.1)
27 | msgpack (1.0.2)
28 | rack (2.0.1)
29 | rack-test (0.6.3)
30 | rack (>= 1.0)
31 | rake (10.5.0)
32 | rspec (3.5.0)
33 | rspec-core (~> 3.5.0)
34 | rspec-expectations (~> 3.5.0)
35 | rspec-mocks (~> 3.5.0)
36 | rspec-core (3.5.4)
37 | rspec-support (~> 3.5.0)
38 | rspec-expectations (3.5.0)
39 | diff-lcs (>= 1.2.0, < 2.0)
40 | rspec-support (~> 3.5.0)
41 | rspec-mocks (3.5.0)
42 | diff-lcs (>= 1.2.0, < 2.0)
43 | rspec-support (~> 3.5.0)
44 | rspec-support (3.5.0)
45 | simplecov (0.12.0)
46 | docile (~> 1.1.0)
47 | json (>= 1.8, < 3)
48 | simplecov-html (~> 0.10.0)
49 | simplecov-html (0.10.0)
50 | thread_safe (0.3.5)
51 | tzinfo (1.2.2)
52 | thread_safe (~> 0.1)
53 | woothee (1.5.0)
54 |
55 | PLATFORMS
56 | ruby
57 |
58 | DEPENDENCIES
59 | bundler (~> 1.13)
60 | codeclimate-test-reporter
61 | rack-action_logger!
62 | rack-test (~> 0.6.3)
63 | rake (~> 10.0)
64 | rspec (~> 3.0)
65 | simplecov
66 |
67 | BUNDLED WITH
68 | 1.15.1
69 |
--------------------------------------------------------------------------------
/example/rails5/public/500.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | We're sorry, but something went wrong (500)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
We're sorry, but something went wrong.
62 |
63 |
If you are the application owner check the logs for more information.
64 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/example/rails5/public/422.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | The change you wanted was rejected (422)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
The change you wanted was rejected.
62 |
Maybe you tried to change something you didn't have access to.
63 |
64 |
If you are the application owner check the logs for more information.
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/example/rails5/public/404.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | The page you were looking for doesn't exist (404)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
The page you were looking for doesn't exist.
62 |
You may have mistyped the address or the page may have moved.
63 |
64 |
If you are the application owner check the logs for more information.
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/example/rails5/config/environments/test.rb:
--------------------------------------------------------------------------------
1 | Rails.application.configure do
2 | # Settings specified here will take precedence over those in config/application.rb.
3 |
4 | # The test environment is used exclusively to run your application's
5 | # test suite. You never need to work with it otherwise. Remember that
6 | # your test database is "scratch space" for the test suite and is wiped
7 | # and recreated between test runs. Don't rely on the data there!
8 | config.cache_classes = true
9 |
10 | # Do not eager load code on boot. This avoids loading your whole application
11 | # just for the purpose of running a single test. If you are using a tool that
12 | # preloads Rails for running tests, you may have to set it to true.
13 | config.eager_load = false
14 |
15 | # Configure public file server for tests with Cache-Control for performance.
16 | config.public_file_server.enabled = true
17 | config.public_file_server.headers = {
18 | 'Cache-Control' => 'public, max-age=3600'
19 | }
20 |
21 | # Show full error reports and disable caching.
22 | config.consider_all_requests_local = true
23 | config.action_controller.perform_caching = false
24 |
25 | # Raise exceptions instead of rendering exception templates.
26 | config.action_dispatch.show_exceptions = false
27 |
28 | # Disable request forgery protection in test environment.
29 | config.action_controller.allow_forgery_protection = false
30 | config.action_mailer.perform_caching = false
31 |
32 | # Tell Action Mailer not to deliver emails to the real world.
33 | # The :test delivery method accumulates sent emails in the
34 | # ActionMailer::Base.deliveries array.
35 | config.action_mailer.delivery_method = :test
36 |
37 | # Print deprecation notices to the stderr.
38 | config.active_support.deprecation = :stderr
39 |
40 | # Raises error for missing translations
41 | # config.action_view.raise_on_missing_translations = true
42 | end
43 |
--------------------------------------------------------------------------------
/lib/rack/action_logger/active_record_extension.rb:
--------------------------------------------------------------------------------
1 | require 'active_support'
2 | require 'active_support/core_ext'
3 |
4 | module Rack::ActionLogger
5 | module ActiveRecordExtension
6 | extend ActiveSupport::Concern
7 |
8 | included do
9 | after_create :capture_action_log_create
10 | after_update :capture_action_log_update
11 | after_destroy :capture_action_log_destroy
12 | end
13 |
14 | def capture_action_log_create
15 | record = { _method: 'create' }
16 | self.class.column_names.each do |column_name|
17 | record["_#{column_name}"] = self.try(column_name)
18 | end
19 | record = Rack::ActionLogger::ParameterFiltering.apply_filter(record)
20 | Rack::ActionLogger::Container.add_append_log(record, "model_#{self.class.table_name}")
21 | end
22 |
23 | def capture_action_log_update
24 | record = { _method: 'update' }
25 | self.class.column_names.each do |column_name|
26 | if column_name.end_with?('_id')
27 | record["_#{column_name}"] = self.try(column_name)
28 | elsif self.try("saved_change_to_#{column_name}?")
29 | record["_after:#{column_name}"] = self.try(column_name)
30 | record["_before:#{column_name}"] = self.try("#{column_name}_before_last_save")
31 | end
32 | end
33 | record = Rack::ActionLogger::ParameterFiltering.apply_filter(record)
34 | Rack::ActionLogger::Container.add_append_log(record, "model_#{self.class.table_name}")
35 | end
36 |
37 | def capture_action_log_destroy
38 | record = { _method: 'delete' }
39 | self.class.column_names.each do |column_name|
40 | if column_name == 'id' || column_name.end_with?('_id')
41 | record["_#{column_name}"] = self.try(column_name)
42 | end
43 | end
44 | record = Rack::ActionLogger::ParameterFiltering.apply_filter(record)
45 | Rack::ActionLogger::Container.add_append_log(record, "model_#{self.class.table_name}")
46 | end
47 | end
48 | end
49 |
--------------------------------------------------------------------------------
/example/rails5/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 |
3 | # Install developed gem
4 | gem 'rack-action_logger', path: '../..'
5 |
6 | gem 'fluent-logger'
7 |
8 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
9 | gem 'rails', '~> 5.1.0'
10 | # Use sqlite3 as the database for Active Record
11 | gem 'sqlite3'
12 | # Use Puma as the app server
13 | gem 'puma', '~> 3.0'
14 | # Use SCSS for stylesheets
15 | gem 'sass-rails', '~> 5.0'
16 | # Use Uglifier as compressor for JavaScript assets
17 | gem 'uglifier', '>= 1.3.0'
18 | # Use CoffeeScript for .coffee assets and views
19 | gem 'coffee-rails', '~> 4.2'
20 | # See https://github.com/rails/execjs#readme for more supported runtimes
21 | # gem 'therubyracer', platforms: :ruby
22 |
23 | # Use jquery as the JavaScript library
24 | gem 'jquery-rails'
25 | # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
26 | gem 'turbolinks', '~> 5'
27 | # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
28 | gem 'jbuilder', '~> 2.5'
29 | # Use Redis adapter to run Action Cable in production
30 | # gem 'redis', '~> 3.0'
31 | # Use ActiveModel has_secure_password
32 | # gem 'bcrypt', '~> 3.1.7'
33 |
34 | # Use Capistrano for deployment
35 | # gem 'capistrano-rails', group: :development
36 |
37 | group :development, :test do
38 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console
39 | gem 'byebug', platform: :mri
40 |
41 | gem 'rspec-rails'
42 | end
43 |
44 | group :development do
45 | # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
46 | gem 'web-console'
47 | gem 'listen', '~> 3.0.5'
48 | # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
49 | gem 'spring'
50 | gem 'spring-watcher-listen', '~> 2.0.0'
51 | end
52 |
53 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
54 | gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
55 |
--------------------------------------------------------------------------------
/example/rails5/config/environments/development.rb:
--------------------------------------------------------------------------------
1 | Rails.application.configure do
2 | # Settings specified here will take precedence over those in config/application.rb.
3 |
4 | # In the development environment your application's code is reloaded on
5 | # every request. This slows down response time but is perfect for development
6 | # since you don't have to restart the web server when you make code changes.
7 | config.cache_classes = false
8 |
9 | # Do not eager load code on boot.
10 | config.eager_load = false
11 |
12 | # Show full error reports.
13 | config.consider_all_requests_local = true
14 |
15 | # Enable/disable caching. By default caching is disabled.
16 | if Rails.root.join('tmp/caching-dev.txt').exist?
17 | config.action_controller.perform_caching = true
18 |
19 | config.cache_store = :memory_store
20 | config.public_file_server.headers = {
21 | 'Cache-Control' => 'public, max-age=172800'
22 | }
23 | else
24 | config.action_controller.perform_caching = false
25 |
26 | config.cache_store = :null_store
27 | end
28 |
29 | # Don't care if the mailer can't send.
30 | config.action_mailer.raise_delivery_errors = false
31 |
32 | config.action_mailer.perform_caching = false
33 |
34 | # Print deprecation notices to the Rails logger.
35 | config.active_support.deprecation = :log
36 |
37 | # Raise an error on page load if there are pending migrations.
38 | config.active_record.migration_error = :page_load
39 |
40 | # Debug mode disables concatenation and preprocessing of assets.
41 | # This option may cause significant delays in view rendering with a large
42 | # number of complex assets.
43 | config.assets.debug = true
44 |
45 | # Suppress logger output for asset requests.
46 | config.assets.quiet = true
47 |
48 | # Raises error for missing translations
49 | # config.action_view.raise_on_missing_translations = true
50 |
51 | # Use an evented file watcher to asynchronously detect changes in source code,
52 | # routes, locales, etc. This feature depends on the listen gem.
53 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker
54 | end
55 |
--------------------------------------------------------------------------------
/example/rails5/config/puma.rb:
--------------------------------------------------------------------------------
1 | # Puma can serve each request in a thread from an internal thread pool.
2 | # The `threads` method setting takes two numbers a minimum and maximum.
3 | # Any libraries that use thread pools should be configured to match
4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum
5 | # and maximum, this matches the default thread size of Active Record.
6 | #
7 | threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i
8 | threads threads_count, threads_count
9 |
10 | # Specifies the `port` that Puma will listen on to receive requests, default is 3000.
11 | #
12 | port ENV.fetch("PORT") { 3000 }
13 |
14 | # Specifies the `environment` that Puma will run in.
15 | #
16 | environment ENV.fetch("RAILS_ENV") { "development" }
17 |
18 | # Specifies the number of `workers` to boot in clustered mode.
19 | # Workers are forked webserver processes. If using threads and workers together
20 | # the concurrency of the application would be max `threads` * `workers`.
21 | # Workers do not work on JRuby or Windows (both of which do not support
22 | # processes).
23 | #
24 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 }
25 |
26 | # Use the `preload_app!` method when specifying a `workers` number.
27 | # This directive tells Puma to first boot the application and load code
28 | # before forking the application. This takes advantage of Copy On Write
29 | # process behavior so workers use less memory. If you use this option
30 | # you need to make sure to reconnect any threads in the `on_worker_boot`
31 | # block.
32 | #
33 | # preload_app!
34 |
35 | # The code in the `on_worker_boot` will be called if you are using
36 | # clustered mode by specifying a number of `workers`. After each worker
37 | # process is booted this block will be run, if you are using `preload_app!`
38 | # option you will want to use this block to reconnect to any threads
39 | # or connections that may have been created at application boot, Ruby
40 | # cannot share connections between processes.
41 | #
42 | # on_worker_boot do
43 | # ActiveRecord::Base.establish_connection if defined?(ActiveRecord)
44 | # end
45 |
46 | # Allow puma to be restarted by `rails restart` command.
47 | plugin :tmp_restart
48 |
--------------------------------------------------------------------------------
/spec/rack/action_logger/parameter_filtering_spec.rb:
--------------------------------------------------------------------------------
1 | require "spec_helper"
2 |
3 | RSpec.describe Rack::ActionLogger::ParameterFiltering do
4 | let(:hash) { { key: 'value' } }
5 | let(:filters) { %w(password secret) }
6 |
7 | before {
8 | described_class.instance_variable_set(:@compiled_filters, nil) # clear filter
9 | Rack::ActionLogger.configure { |c| c.filters = filters }
10 | }
11 |
12 | describe 'compile' do
13 | it 'should be success' do
14 | expect(described_class.send(:compile, filters)).not_to be_nil
15 | end
16 | end
17 |
18 | describe 'apply_filter' do
19 | it 'should not filter with un-filter key' do
20 | expect(described_class.apply_filter(hash)).to eq hash
21 | end
22 |
23 | it 'should filter hash with filter keys' do
24 | filtered_hash = {
25 | password: 'password',
26 | secret: 'secret',
27 | un_filter: 'value'
28 | }
29 | expected_filtered_hash = {
30 | password: "#{described_class::FILTERED}",
31 | secret: "#{described_class::FILTERED}",
32 | un_filter: 'value'
33 | }
34 | expect(described_class.apply_filter(filtered_hash)).to eq expected_filtered_hash
35 | end
36 |
37 | it 'should filter hash array with filter keys' do
38 | filtered_hash = {
39 | values: [
40 | password: 'password',
41 | secret: 'secret',
42 | un_filter: 'value'
43 | ]
44 | }
45 | expected_filtered_hash = {
46 | values: [
47 | password: "#{described_class::FILTERED}",
48 | secret: "#{described_class::FILTERED}",
49 | un_filter: 'value'
50 | ]
51 | }
52 | expect(described_class.apply_filter(filtered_hash)).to eq expected_filtered_hash
53 | end
54 |
55 | it 'should filter hash array with filter keys containing underscore' do
56 | filtered_hash = {
57 | values: [
58 | _password: 'password',
59 | secret: 'secret',
60 | un_filter: 'value'
61 | ]
62 | }
63 | expected_filtered_hash = {
64 | values: [
65 | _password: "#{described_class::FILTERED}",
66 | secret: "#{described_class::FILTERED}",
67 | un_filter: 'value'
68 | ]
69 | }
70 | expect(described_class.apply_filter(filtered_hash)).to eq expected_filtered_hash
71 | end
72 |
73 | end
74 | end
75 |
--------------------------------------------------------------------------------
/spec/rack/action_logger/emitter_spec.rb:
--------------------------------------------------------------------------------
1 | require "spec_helper"
2 |
3 | RSpec.describe Rack::ActionLogger::Emitter do
4 | let(:hash) { { key: 'value' } }
5 | let(:tag) { 'tag' }
6 | before { Rack::ActionLogger::Container.clear }
7 |
8 | describe 'emit' do
9 | it 'can be initialize' do
10 | expect(described_class.new).to be_an_instance_of(described_class)
11 | end
12 |
13 | it 'can emit without log' do
14 | expect { described_class.new.emit {} }.not_to raise_error
15 | end
16 |
17 | it 'can emit with log' do
18 | Rack::ActionLogger::Container.set_request_log(hash, tag)
19 | expect{ described_class.new.emit {} }.not_to raise_error
20 | end
21 |
22 | it 'can be nested but logged error' do
23 | adapter_mock = double('Emit Adapter')
24 | expected = hash.merge({ tag: "#{Rack::ActionLogger.configuration.tag_prefix}.#{tag}" })
25 | expect(adapter_mock).to receive(:emit).with(expected)
26 | Rack::ActionLogger::Container.set_request_log(hash, tag)
27 | emitter = described_class.new
28 | emitter.instance_variable_set(:@emit_adapter, adapter_mock)
29 | emitter.emit {}
30 | end
31 |
32 | it 'should clear container after emit' do
33 | Rack::ActionLogger::Container.set_request_log(hash, tag)
34 | expect(Rack::ActionLogger::Container.send(:store)).not_to be_empty
35 | described_class.new.emit {}
36 | expect(Rack::ActionLogger::Container.send(:store)).to be_empty
37 | end
38 |
39 | it 'should clear container after emit with exception' do
40 | Rack::ActionLogger::Container.set_request_log(hash, tag)
41 | expect(Rack::ActionLogger::Container.send(:store)).not_to be_empty
42 | expect{ described_class.new.emit { raise StandardError } }.to raise_error(StandardError)
43 | expect(Rack::ActionLogger::Container.send(:store)).to be_empty
44 | end
45 | end
46 |
47 | describe 'format_tag' do
48 | it 'should return correct tag without tag' do
49 | Rack::ActionLogger.configure { |c| c.tag_prefix = 'access' }
50 | hash = {}
51 | expect(described_class.new.send(:format_tag, hash)[:tag]).to eq Rack::ActionLogger.configuration.default_tag
52 | end
53 |
54 | it 'should return correct tag with tag' do
55 | Rack::ActionLogger.configure { |c| c.tag_prefix = 'access' }
56 | hash = { tag: 'tag' }
57 | expect(described_class.new.send(:format_tag, hash)[:tag]).to eq 'access.tag'
58 | end
59 |
60 | it 'should return correct tag without tag_prefix' do
61 | Rack::ActionLogger.configure { |c| c.tag_prefix = nil }
62 | hash = {}
63 | expect(described_class.new.send(:format_tag, hash)[:tag]).to eq Rack::ActionLogger.configuration.default_tag
64 | end
65 | end
66 | end
67 |
--------------------------------------------------------------------------------
/lib/rack/action_logger/container.rb:
--------------------------------------------------------------------------------
1 | require 'active_support'
2 | require 'active_support/core_ext'
3 |
4 | module Rack::ActionLogger
5 | module Container
6 | THREAD_KEY = :rack_action_logger
7 | EXPORT_KEYS = [:rack_action_logger_attributes]
8 |
9 | class << self
10 |
11 | def clear
12 | Thread.current[THREAD_KEY] = nil
13 | end
14 |
15 | def is_emit_started=(value)
16 | store[:rack_action_logger_emit_started] = value
17 | end
18 |
19 | def is_emit_started
20 | store[:rack_action_logger_emit_started] ||= false
21 | end
22 |
23 | def add_append_log(hash, tag=nil)
24 | return unless is_valid_hash hash
25 | return unless is_valid_tag tag
26 | hash[:tag] = tag
27 | append_logs.push(hash)
28 | end
29 |
30 | def append_logs
31 | store[:rack_action_logger_append_logs] ||= []
32 | end
33 |
34 | def merge_attributes(attributes)
35 | return unless is_valid_hash attributes
36 | self.attributes = self.attributes.merge! attributes
37 | end
38 |
39 | def attributes
40 | store[:rack_action_logger_attributes] ||= {}
41 | end
42 |
43 | def set_request_log(hash, tag=nil)
44 | return unless is_valid_hash hash
45 | return unless is_valid_tag tag
46 | hash[:tag] = tag
47 | self.request_log = hash
48 | end
49 |
50 | def request_log
51 | store[:rack_action_logger_request_log] ||= {}
52 | end
53 |
54 | def export
55 | EXPORT_KEYS.inject({}) do |result, key|
56 | result[key] = store[key] if store[key]
57 | result
58 | end
59 | end
60 |
61 | def import(hash)
62 | hash.symbolize_keys.each do |key, value|
63 | next unless EXPORT_KEYS.include? key
64 | store[key] = value
65 | end
66 | end
67 |
68 | private
69 |
70 | def store
71 | Thread.current[THREAD_KEY] ||= {}
72 | end
73 |
74 | def is_valid_hash(hash)
75 | if hash.is_a? Hash
76 | true
77 | else
78 | Rack::ActionLogger.logger.error("invalid hash: #{hash}")
79 | false
80 | end
81 | end
82 |
83 | def is_valid_tag(tag)
84 | if tag.nil? || tag.is_a?(String)
85 | true
86 | else
87 | Rack::ActionLogger.logger.error("invalid tag: #{tag}")
88 | false
89 | end
90 | end
91 |
92 | def attributes=(value)
93 | store[:rack_action_logger_attributes] = value
94 | end
95 |
96 | def request_log=(value)
97 | store[:rack_action_logger_request_log] = value
98 | end
99 | end
100 |
101 | end
102 | end
103 |
--------------------------------------------------------------------------------
/example/rails5/spec/rails_helper.rb:
--------------------------------------------------------------------------------
1 | # This file is copied to spec/ when you run 'rails generate rspec:install'
2 | ENV['RAILS_ENV'] ||= 'test'
3 | require File.expand_path('../../config/environment', __FILE__)
4 | # Prevent database truncation if the environment is production
5 | abort("The Rails environment is running in production mode!") if Rails.env.production?
6 | require 'spec_helper'
7 | require 'rspec/rails'
8 | # Add additional requires below this line. Rails is not loaded until this point!
9 |
10 | # Requires supporting ruby files with custom matchers and macros, etc, in
11 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
12 | # run as spec files by default. This means that files in spec/support that end
13 | # in _spec.rb will both be required and run as specs, causing the specs to be
14 | # run twice. It is recommended that you do not name files matching this glob to
15 | # end with _spec.rb. You can configure this pattern with the --pattern
16 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
17 | #
18 | # The following line is provided for convenience purposes. It has the downside
19 | # of increasing the boot-up time by auto-requiring all files in the support
20 | # directory. Alternatively, in the individual `*_spec.rb` files, manually
21 | # require only the support files necessary.
22 | #
23 | # Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
24 |
25 | # Checks for pending migration and applies them before tests are run.
26 | # If you are not using ActiveRecord, you can remove this line.
27 | ActiveRecord::Migration.maintain_test_schema!
28 |
29 | RSpec.configure do |config|
30 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
31 | config.fixture_path = "#{::Rails.root}/spec/fixtures"
32 |
33 | # If you're not using ActiveRecord, or you'd prefer not to run each of your
34 | # examples within a transaction, remove the following line or assign false
35 | # instead of true.
36 | config.use_transactional_fixtures = true
37 |
38 | # RSpec Rails can automatically mix in different behaviours to your tests
39 | # based on their file location, for example enabling you to call `get` and
40 | # `post` in specs under `spec/controllers`.
41 | #
42 | # You can disable this behaviour by removing the line below, and instead
43 | # explicitly tag your specs with their type, e.g.:
44 | #
45 | # RSpec.describe UsersController, :type => :controller do
46 | # # ...
47 | # end
48 | #
49 | # The different available types are documented in the features, such as in
50 | # https://relishapp.com/rspec/rspec-rails/docs
51 | config.infer_spec_type_from_file_location!
52 |
53 | # Filter lines from Rails gems in backtraces.
54 | config.filter_rails_from_backtrace!
55 | # arbitrary gems may also be filtered via:
56 | # config.filter_gems_from_backtrace("gem name")
57 | end
58 |
--------------------------------------------------------------------------------
/spec/rack/action_logger/active_record_extension_spec.rb:
--------------------------------------------------------------------------------
1 | require "spec_helper"
2 |
3 | RSpec.describe Rack::ActionLogger::ActiveRecordExtension do
4 | let(:target_class) { Struct.new(:action_record_extension) { include described_class } }
5 | let(:target) { target_class.new }
6 | let(:column_names) { %w(password key article_id) }
7 |
8 | before {
9 | described_class.instance_variable_set(:@compiled_filters, nil) # clear filter
10 | Rack::ActionLogger.configure { |c| c.filters = ['password'] }
11 |
12 | Rack::ActionLogger::Container.clear
13 | @active_record_mock = double('Active Record')
14 | allow(@active_record_mock.class).to receive(:after_create)
15 | allow(@active_record_mock.class).to receive(:after_update)
16 | allow(@active_record_mock.class).to receive(:after_destroy)
17 | allow(@active_record_mock.class).to receive(:column_names).and_return(column_names)
18 | allow(@active_record_mock.class).to receive(:table_name).and_return('table_name')
19 | allow(@active_record_mock).to receive(:password).and_return('password')
20 | allow(@active_record_mock).to receive(:saved_change_to_password?).and_return(true)
21 | allow(@active_record_mock).to receive(:password_before_last_save).and_return('old_password')
22 | allow(@active_record_mock).to receive(:key).and_return('key')
23 | allow(@active_record_mock).to receive(:saved_change_to_key?).and_return(false)
24 | allow(@active_record_mock).to receive(:article_id).and_return(1234)
25 | allow(@active_record_mock).to receive(:saved_change_to_article_id?).and_return(false)
26 | }
27 |
28 | describe 'capture_action_log_create' do
29 | it do
30 | expected = [{
31 | _method: 'create',
32 | '_password' => Rack::ActionLogger::ParameterFiltering::FILTERED,
33 | '_key' => 'key',
34 | '_article_id' => 1234,
35 | tag: 'model_table_name'
36 | }]
37 | @active_record_mock.class.send(:include, described_class)
38 | @active_record_mock.capture_action_log_create
39 | expect(Rack::ActionLogger::Container.append_logs).to eq expected
40 | end
41 | end
42 |
43 | describe 'capture_action_log_update' do
44 | it do
45 | expected = [{
46 | _method: 'update',
47 | '_after:password' => Rack::ActionLogger::ParameterFiltering::FILTERED,
48 | '_before:password' => Rack::ActionLogger::ParameterFiltering::FILTERED,
49 | '_article_id' => 1234,
50 | tag: 'model_table_name'
51 | }]
52 | @active_record_mock.class.send(:include, described_class)
53 | @active_record_mock.capture_action_log_update
54 | expect(Rack::ActionLogger::Container.append_logs).to eq expected
55 | end
56 | end
57 |
58 | describe 'capture_action_log_destroy' do
59 | it do
60 | expected = [{
61 | _method: 'delete',
62 | '_article_id' => 1234,
63 | tag: 'model_table_name'
64 | }]
65 | @active_record_mock.class.send(:include, described_class)
66 | @active_record_mock.capture_action_log_destroy
67 | expect(Rack::ActionLogger::Container.append_logs).to eq expected
68 | end
69 | end
70 | end
71 |
--------------------------------------------------------------------------------
/lib/rack/action_logger/metrics/rack_metrics.rb:
--------------------------------------------------------------------------------
1 | require 'rack/action_logger'
2 | require 'rack/mock'
3 | require 'woothee'
4 |
5 | module Rack::ActionLogger::Metrics
6 | class RackMetrics
7 | METRICS = [
8 | :path, :method, :params, :request_headers, :status_code, :ip, :remote_ip, :user_agent, :device, :os, :browser,
9 | :browser_version, :request_id, :response_headers, :response_json_body,
10 | ]
11 | RACK_TAG_PREFIX = 'rack'
12 | EXCLUDE_PATH_PREFIX = '/asset'
13 |
14 | attr_reader :status_code
15 |
16 | def initialize(env, status_code, headers, body)
17 | @env = env
18 | @status_code = status_code
19 | @headers = headers
20 | @body = body
21 | @request = Rack::Request.new(env)
22 | @response = Rack::Response.new(body, status_code, headers)
23 | @ua = Woothee.parse(@request.user_agent)
24 | end
25 |
26 | def tag_suffix
27 | return RACK_TAG_PREFIX if Rack::ActionLogger.configuration.rack_unified_tag
28 | if @status_code == 404
29 | tags = ['not_found']
30 | else
31 | tags = URI(path).path.split('/').reject { |c| c.empty? }
32 | end
33 | (Array(RACK_TAG_PREFIX) + tags).join('.')
34 | end
35 |
36 | def metrics
37 | return unless enable_metrics
38 | METRICS.inject({}) do |result, metric|
39 | result[metric] = self.send(metric) unless
40 | Rack::ActionLogger.configuration.rack_request_blacklist.include? metric
41 | result
42 | end
43 | end
44 |
45 | def path
46 | @request.path
47 | end
48 |
49 | def method
50 | @request.request_method
51 | end
52 |
53 | def params
54 | Rack::ActionLogger::ParameterFiltering.apply_filter(@request.params)
55 | end
56 |
57 | def request_headers
58 | @env.select { |v| v.start_with? 'HTTP_' }
59 | end
60 |
61 | def enable_metrics
62 | Rack::ActionLogger.configuration.rack_content_types.any? { |c| content_type.to_s.include?(c) } || action_controller
63 | end
64 |
65 | def action_controller
66 | @env['action_controller.instance']
67 | end
68 |
69 | def content_type
70 | @response.content_type
71 | end
72 |
73 | def remote_ip
74 | @env['action_dispatch.remote_ip']
75 | end
76 |
77 | def ip
78 | @request.ip
79 | end
80 |
81 | def user_agent
82 | @request.user_agent
83 | end
84 |
85 | def device
86 | @ua[:category]
87 | end
88 |
89 | def os
90 | @ua[:os]
91 | end
92 |
93 | def browser
94 | @ua[:name]
95 | end
96 |
97 | def browser_version
98 | @ua[:version]
99 | end
100 |
101 | def request_id
102 | @env['action_dispatch.request_id']
103 | end
104 |
105 | def response_headers
106 | @headers
107 | end
108 |
109 | def response_json_body
110 | response_bodies = []
111 | @body.each { |part| response_bodies << part } if @body
112 | result = JSON.parse(response_bodies.join('')) rescue {}
113 | Rack::ActionLogger::ParameterFiltering.apply_filter(result)
114 | end
115 | end
116 | end
117 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, gender identity and expression, level of experience,
9 | nationality, personal appearance, race, religion, or sexual identity and
10 | orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ## Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project team at wapa5pow@gmail.com. All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ## Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at [http://contributor-covenant.org/version/1/4][version]
72 |
73 | [homepage]: http://contributor-covenant.org
74 | [version]: http://contributor-covenant.org/version/1/4/
75 |
--------------------------------------------------------------------------------
/example/rails5/config/environments/production.rb:
--------------------------------------------------------------------------------
1 | Rails.application.configure do
2 | # Settings specified here will take precedence over those in config/application.rb.
3 |
4 | # Code is not reloaded between requests.
5 | config.cache_classes = true
6 |
7 | # Eager load code on boot. This eager loads most of Rails and
8 | # your application in memory, allowing both threaded web servers
9 | # and those relying on copy on write to perform better.
10 | # Rake tasks automatically ignore this option for performance.
11 | config.eager_load = true
12 |
13 | # Full error reports are disabled and caching is turned on.
14 | config.consider_all_requests_local = false
15 | config.action_controller.perform_caching = true
16 |
17 | # Disable serving static files from the `/public` folder by default since
18 | # Apache or NGINX already handles this.
19 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
20 |
21 | # Compress JavaScripts and CSS.
22 | config.assets.js_compressor = :uglifier
23 | # config.assets.css_compressor = :sass
24 |
25 | # Do not fallback to assets pipeline if a precompiled asset is missed.
26 | config.assets.compile = false
27 |
28 | # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
29 |
30 | # Enable serving of images, stylesheets, and JavaScripts from an asset server.
31 | # config.action_controller.asset_host = 'http://assets.example.com'
32 |
33 | # Specifies the header that your server uses for sending files.
34 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
35 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
36 |
37 | # Mount Action Cable outside main process or domain
38 | # config.action_cable.mount_path = nil
39 | # config.action_cable.url = 'wss://example.com/cable'
40 | # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
41 |
42 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
43 | # config.force_ssl = true
44 |
45 | # Use the lowest log level to ensure availability of diagnostic information
46 | # when problems arise.
47 | config.log_level = :debug
48 |
49 | # Prepend all log lines with the following tags.
50 | config.log_tags = [ :request_id ]
51 |
52 | # Use a different cache store in production.
53 | # config.cache_store = :mem_cache_store
54 |
55 | # Use a real queuing backend for Active Job (and separate queues per environment)
56 | # config.active_job.queue_adapter = :resque
57 | # config.active_job.queue_name_prefix = "rails_example_#{Rails.env}"
58 | config.action_mailer.perform_caching = false
59 |
60 | # Ignore bad email addresses and do not raise email delivery errors.
61 | # Set this to true and configure the email server for immediate delivery to raise delivery errors.
62 | # config.action_mailer.raise_delivery_errors = false
63 |
64 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
65 | # the I18n.default_locale when a translation cannot be found).
66 | config.i18n.fallbacks = true
67 |
68 | # Send deprecation notices to registered listeners.
69 | config.active_support.deprecation = :notify
70 |
71 | # Use default logging formatter so that PID and timestamp are not suppressed.
72 | config.log_formatter = ::Logger::Formatter.new
73 |
74 | # Use a different logger for distributed setups.
75 | # require 'syslog/logger'
76 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
77 |
78 | if ENV["RAILS_LOG_TO_STDOUT"].present?
79 | logger = ActiveSupport::Logger.new(STDOUT)
80 | logger.formatter = config.log_formatter
81 | config.logger = ActiveSupport::TaggedLogging.new(logger)
82 | end
83 |
84 | # Do not dump schema after migrations.
85 | config.active_record.dump_schema_after_migration = false
86 | end
87 |
--------------------------------------------------------------------------------
/spec/rack/action_logger/metrics/rack_metrics_spec.rb:
--------------------------------------------------------------------------------
1 | require "spec_helper"
2 |
3 | RSpec.describe Rack::ActionLogger::Metrics::RackMetrics do
4 | let(:user_agent) { 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10' }
5 | let(:env) { Rack::MockRequest.env_for('/path/to?key=value', 'HTTP_USER_AGENT' => user_agent) }
6 | let(:status_code) { 200 }
7 | let(:response_header) { { 'content-length' => 5869, 'content-type' => 'text/html' } }
8 | let(:response_body) { [{'key' => 'body'}.to_json.to_s] }
9 | let(:ip) { '127.0.0.1' }
10 | let(:target) {
11 | env['REMOTE_ADDR'] = ip
12 | described_class.new(env, status_code, response_header, response_body)
13 | }
14 |
15 | describe 'new' do
16 | it 'should initialize instance' do
17 | expect(described_class.new(env, status_code, response_header, response_body)).not_to be_nil
18 | end
19 | end
20 |
21 | describe 'tag_suffix' do
22 | it 'should return separate tag' do
23 | Rack::ActionLogger.configure { |config| config.rack_unified_tag = false }
24 | expect(target.tag_suffix).to eq "#{described_class::RACK_TAG_PREFIX}.path.to"
25 | end
26 |
27 | it 'should return unified tag' do
28 | Rack::ActionLogger.configure { |config| config.rack_unified_tag = true }
29 | expect(target.tag_suffix).to eq "#{described_class::RACK_TAG_PREFIX}"
30 | end
31 | end
32 |
33 | describe 'metrics' do
34 | it 'should have all keys' do
35 | Rack::ActionLogger.configure { |config| config.rack_request_blacklist = [] }
36 | metrics = target.metrics
37 | described_class::METRICS.each do |metric|
38 | expect(metrics).to have_key(metric)
39 | end
40 | end
41 |
42 | it 'should not have blacklist key' do
43 | blacklist_key = :path
44 | Rack::ActionLogger.configure do |config|
45 | config.rack_request_blacklist = [blacklist_key]
46 | end
47 | metrics = target.metrics
48 | described_class::METRICS.each do |metric|
49 | if metric == blacklist_key
50 | expect(metrics).not_to have_key(metric)
51 | else
52 | expect(metrics).to have_key(metric)
53 | end
54 | end
55 | end
56 | end
57 |
58 | describe 'path' do
59 | it do
60 | expect(target.path).to eq '/path/to'
61 | end
62 | end
63 |
64 | describe 'method' do
65 | it do
66 | expect(target.method).to eq 'GET'
67 | end
68 | end
69 |
70 | describe 'params' do
71 | it do
72 | expect(target.params).to eq({ 'key' => 'value' })
73 | end
74 | end
75 |
76 | describe 'request_headers' do
77 | it do
78 | expect(target.request_headers).to eq({ 'HTTP_USER_AGENT' => user_agent })
79 | end
80 | end
81 |
82 | describe 'remote_ip' do
83 | it do
84 | expect(target.remote_ip).to eq nil
85 | end
86 | end
87 |
88 | describe 'ip' do
89 | it do
90 | expect(target.ip).to eq ip
91 | end
92 | end
93 |
94 | describe 'user_agent' do
95 | it do
96 | expect(target.user_agent).to eq user_agent
97 | end
98 | end
99 |
100 | describe 'device' do
101 | it do
102 | expect(target.device).to eq :smartphone
103 | end
104 | end
105 |
106 | describe 'os' do
107 | it do
108 | expect(target.os).to eq 'iPad'
109 | end
110 | end
111 |
112 |
113 | describe 'browser' do
114 | it do
115 | expect(target.browser).to eq 'Safari'
116 | end
117 | end
118 |
119 | describe 'browser_version' do
120 | it do
121 | expect(target.browser_version).to eq '4.0.4'
122 | end
123 | end
124 |
125 | describe 'response_headers' do
126 | it do
127 | expect(target.response_headers).to eq response_header
128 | end
129 | end
130 |
131 | describe 'response_json_body' do
132 | it do
133 | expect(target.response_json_body).to eq({ 'key' => 'body' })
134 | end
135 | end
136 |
137 | end
138 |
--------------------------------------------------------------------------------
/spec/rack/action_logger/container_spec.rb:
--------------------------------------------------------------------------------
1 | require "spec_helper"
2 |
3 | RSpec.describe Rack::ActionLogger::Container do
4 | let(:hash) { { key: 'value' } }
5 | let(:tag) { 'tag' }
6 | before { described_class.clear }
7 |
8 | describe 'store' do
9 | it 'should return empty hash as default' do
10 | expect(described_class.send(:store)).to be {}
11 | end
12 | end
13 |
14 | describe 'is_emit_started' do
15 | it 'should return false as default' do
16 | expect(described_class.is_emit_started).to be_falsy
17 | end
18 |
19 | it 'should return true after set' do
20 | described_class.is_emit_started = true
21 | expect(described_class.is_emit_started).to be_truthy
22 | end
23 | end
24 |
25 | describe 'append_log' do
26 | it 'should return empty hash as default' do
27 | expect(described_class.append_logs).to eq []
28 | end
29 |
30 | it 'can append log' do
31 | described_class.add_append_log(hash, tag)
32 | expected = [hash.merge({ tag: tag })]
33 | expect(described_class.append_logs).to eq expected
34 | end
35 |
36 | it 'can be the same object after changed' do
37 | append_log = described_class.append_logs
38 | described_class.add_append_log(hash, tag)
39 | expect(described_class.append_logs).to be append_log
40 | end
41 |
42 | it 'should log with nil tag' do
43 | expected = [hash.merge({ tag: nil })]
44 | described_class.add_append_log(hash)
45 | expect(described_class.append_logs).to eq expected
46 | end
47 |
48 | it 'should not log without invalid tag' do
49 | described_class.add_append_log(hash, ['test'])
50 | expect(described_class.append_logs).to eq []
51 | end
52 |
53 | it 'should not log without invalid hash' do
54 | described_class.add_append_log(nil, tag)
55 | expect(described_class.append_logs).to eq []
56 | end
57 | end
58 |
59 | describe 'attributes' do
60 | it 'should return empty hash as default' do
61 | expect(described_class.attributes).to be {}
62 | end
63 |
64 | it 'can merge attributes' do
65 | described_class.merge_attributes(hash)
66 | expect(described_class.attributes).to eq hash
67 | end
68 |
69 | it 'can be the same object after changed' do
70 | attributes = described_class.attributes
71 | described_class.merge_attributes(hash)
72 | expect(described_class.attributes).to be attributes
73 | end
74 |
75 | it 'should not log without invalid hash' do
76 | described_class.merge_attributes(nil)
77 | expect(described_class.attributes).to be {}
78 | end
79 | end
80 |
81 | describe 'request_log' do
82 | it 'should return empty hash as default' do
83 | expect(described_class.request_log).to be {}
84 | end
85 |
86 | it 'can get request log' do
87 | described_class.set_request_log(hash, tag)
88 | expected = hash.merge({ tag: tag })
89 | expect(described_class.request_log).to eq expected
90 | end
91 |
92 | it 'can be the same object after changed' do
93 | expected = hash.merge({ tag: tag })
94 | described_class.set_request_log(hash, tag)
95 | expect(described_class.request_log).to eq expected
96 | end
97 |
98 | it 'should not log without invalid hash' do
99 | described_class.set_request_log(hash, ['test'])
100 | expect(described_class.request_log).to be {}
101 | end
102 |
103 | it 'should log with nil tag' do
104 | expected = hash.merge({ tag: nil })
105 | described_class.set_request_log(hash)
106 | expect(described_class.request_log).to eq expected
107 | end
108 |
109 | it 'should not log without invalid tag' do
110 | described_class.set_request_log(nil, tag)
111 | expect(described_class.request_log).to be {}
112 | end
113 | end
114 |
115 | describe 'import/export' do
116 | it 'can export with no attribute' do
117 | expect(described_class.export).to be {}
118 | end
119 |
120 | it 'can export with attributes' do
121 | expected_hash = { rack_action_logger_attributes: hash }
122 | described_class.merge_attributes(hash)
123 | expect(described_class.export).to eq expected_hash
124 | end
125 |
126 | it 'can import' do
127 | expected_hash = { rack_action_logger_attributes: hash }
128 | described_class.import(expected_hash)
129 | expect(described_class.export).to eq expected_hash
130 | end
131 |
132 | it 'can import non symbol key hash' do
133 | expected_hash = { 'rack_action_logger_attributes': hash }
134 | described_class.import(expected_hash)
135 | expect(described_class.export).to eq expected_hash
136 | end
137 | end
138 | end
139 |
--------------------------------------------------------------------------------
/example/rails5/spec/spec_helper.rb:
--------------------------------------------------------------------------------
1 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all
2 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
3 | # The generated `.rspec` file contains `--require spec_helper` which will cause
4 | # this file to always be loaded, without a need to explicitly require it in any
5 | # files.
6 | #
7 | # Given that it is always loaded, you are encouraged to keep this file as
8 | # light-weight as possible. Requiring heavyweight dependencies from this file
9 | # will add to the boot time of your test suite on EVERY test run, even for an
10 | # individual file that may not need all of that loaded. Instead, consider making
11 | # a separate helper file that requires the additional dependencies and performs
12 | # the additional setup, and require it from the spec files that actually need
13 | # it.
14 | #
15 | # The `.rspec` file also contains a few flags that are not defaults but that
16 | # users commonly want.
17 | #
18 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
19 | RSpec.configure do |config|
20 | # rspec-expectations config goes here. You can use an alternate
21 | # assertion/expectation library such as wrong or the stdlib/minitest
22 | # assertions if you prefer.
23 | config.expect_with :rspec do |expectations|
24 | # This option will default to `true` in RSpec 4. It makes the `description`
25 | # and `failure_message` of custom matchers include text for helper methods
26 | # defined using `chain`, e.g.:
27 | # be_bigger_than(2).and_smaller_than(4).description
28 | # # => "be bigger than 2 and smaller than 4"
29 | # ...rather than:
30 | # # => "be bigger than 2"
31 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true
32 | end
33 |
34 | # rspec-mocks config goes here. You can use an alternate test double
35 | # library (such as bogus or mocha) by changing the `mock_with` option here.
36 | config.mock_with :rspec do |mocks|
37 | # Prevents you from mocking or stubbing a method that does not exist on
38 | # a real object. This is generally recommended, and will default to
39 | # `true` in RSpec 4.
40 | mocks.verify_partial_doubles = true
41 | end
42 |
43 | # This option will default to `:apply_to_host_groups` in RSpec 4 (and will
44 | # have no way to turn it off -- the option exists only for backwards
45 | # compatibility in RSpec 3). It causes shared context metadata to be
46 | # inherited by the metadata hash of host groups and examples, rather than
47 | # triggering implicit auto-inclusion in groups with matching metadata.
48 | config.shared_context_metadata_behavior = :apply_to_host_groups
49 |
50 | # The settings below are suggested to provide a good initial experience
51 | # with RSpec, but feel free to customize to your heart's content.
52 | =begin
53 | # This allows you to limit a spec run to individual examples or groups
54 | # you care about by tagging them with `:focus` metadata. When nothing
55 | # is tagged with `:focus`, all examples get run. RSpec also provides
56 | # aliases for `it`, `describe`, and `context` that include `:focus`
57 | # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
58 | config.filter_run_when_matching :focus
59 |
60 | # Allows RSpec to persist some state between runs in order to support
61 | # the `--only-failures` and `--next-failure` CLI options. We recommend
62 | # you configure your source control system to ignore this file.
63 | config.example_status_persistence_file_path = "spec/examples.txt"
64 |
65 | # Limits the available syntax to the non-monkey patched syntax that is
66 | # recommended. For more details, see:
67 | # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
68 | # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
69 | # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
70 | config.disable_monkey_patching!
71 |
72 | # Many RSpec users commonly either run the entire suite or an individual
73 | # file, and it's useful to allow more verbose output when running an
74 | # individual spec file.
75 | if config.files_to_run.one?
76 | # Use the documentation formatter for detailed output,
77 | # unless a formatter has already been configured
78 | # (e.g. via a command-line flag).
79 | config.default_formatter = 'doc'
80 | end
81 |
82 | # Print the 10 slowest examples and example groups at the
83 | # end of the spec run, to help surface which specs are running
84 | # particularly slow.
85 | config.profile_examples = 10
86 |
87 | # Run specs in random order to surface order dependencies. If you find an
88 | # order dependency and want to debug it, you can fix the order by providing
89 | # the seed, which is printed after each run.
90 | # --seed 1234
91 | config.order = :random
92 |
93 | # Seed global randomization in this process using the `--seed` CLI option.
94 | # Setting this allows you to use `--seed` to deterministically reproduce
95 | # test failures related to randomization by passing the same `--seed` value
96 | # as the one that triggered the failure.
97 | Kernel.srand config.seed
98 | =end
99 | end
100 |
--------------------------------------------------------------------------------
/example/rails5/Gemfile.lock:
--------------------------------------------------------------------------------
1 | PATH
2 | remote: ../..
3 | specs:
4 | rack-action_logger (0.4.0)
5 | activesupport
6 | fluent-logger (~> 0.5)
7 | woothee (~> 1.4)
8 |
9 | GEM
10 | remote: https://rubygems.org/
11 | specs:
12 | actioncable (5.1.6)
13 | actionpack (= 5.1.6)
14 | nio4r (~> 2.0)
15 | websocket-driver (~> 0.6.1)
16 | actionmailer (5.1.6)
17 | actionpack (= 5.1.6)
18 | actionview (= 5.1.6)
19 | activejob (= 5.1.6)
20 | mail (~> 2.5, >= 2.5.4)
21 | rails-dom-testing (~> 2.0)
22 | actionpack (5.1.6)
23 | actionview (= 5.1.6)
24 | activesupport (= 5.1.6)
25 | rack (~> 2.0)
26 | rack-test (>= 0.6.3)
27 | rails-dom-testing (~> 2.0)
28 | rails-html-sanitizer (~> 1.0, >= 1.0.2)
29 | actionview (5.1.6)
30 | activesupport (= 5.1.6)
31 | builder (~> 3.1)
32 | erubi (~> 1.4)
33 | rails-dom-testing (~> 2.0)
34 | rails-html-sanitizer (~> 1.0, >= 1.0.3)
35 | activejob (5.1.6)
36 | activesupport (= 5.1.6)
37 | globalid (>= 0.3.6)
38 | activemodel (5.1.6)
39 | activesupport (= 5.1.6)
40 | activerecord (5.1.6)
41 | activemodel (= 5.1.6)
42 | activesupport (= 5.1.6)
43 | arel (~> 8.0)
44 | activesupport (5.1.6)
45 | concurrent-ruby (~> 1.0, >= 1.0.2)
46 | i18n (>= 0.7, < 2)
47 | minitest (~> 5.1)
48 | tzinfo (~> 1.1)
49 | arel (8.0.0)
50 | bindex (0.5.0)
51 | builder (3.2.3)
52 | byebug (10.0.2)
53 | coffee-rails (4.2.2)
54 | coffee-script (>= 2.2.0)
55 | railties (>= 4.0.0)
56 | coffee-script (2.4.1)
57 | coffee-script-source
58 | execjs
59 | coffee-script-source (1.12.2)
60 | concurrent-ruby (1.0.5)
61 | crass (1.0.4)
62 | diff-lcs (1.3)
63 | erubi (1.7.1)
64 | execjs (2.7.0)
65 | ffi (1.9.25)
66 | fluent-logger (0.7.2)
67 | msgpack (>= 1.0.0, < 2)
68 | globalid (0.4.1)
69 | activesupport (>= 4.2.0)
70 | i18n (1.1.0)
71 | concurrent-ruby (~> 1.0)
72 | jbuilder (2.7.0)
73 | activesupport (>= 4.2.0)
74 | multi_json (>= 1.2)
75 | jquery-rails (4.3.3)
76 | rails-dom-testing (>= 1, < 3)
77 | railties (>= 4.2.0)
78 | thor (>= 0.14, < 2.0)
79 | listen (3.0.8)
80 | rb-fsevent (~> 0.9, >= 0.9.4)
81 | rb-inotify (~> 0.9, >= 0.9.7)
82 | loofah (2.2.2)
83 | crass (~> 1.0.2)
84 | nokogiri (>= 1.5.9)
85 | mail (2.7.0)
86 | mini_mime (>= 0.1.1)
87 | method_source (0.9.0)
88 | mini_mime (1.0.0)
89 | mini_portile2 (2.3.0)
90 | minitest (5.11.3)
91 | msgpack (1.2.4)
92 | multi_json (1.13.1)
93 | nio4r (2.3.1)
94 | nokogiri (1.8.4)
95 | mini_portile2 (~> 2.3.0)
96 | puma (3.12.0)
97 | rack (2.0.5)
98 | rack-test (1.1.0)
99 | rack (>= 1.0, < 3)
100 | rails (5.1.6)
101 | actioncable (= 5.1.6)
102 | actionmailer (= 5.1.6)
103 | actionpack (= 5.1.6)
104 | actionview (= 5.1.6)
105 | activejob (= 5.1.6)
106 | activemodel (= 5.1.6)
107 | activerecord (= 5.1.6)
108 | activesupport (= 5.1.6)
109 | bundler (>= 1.3.0)
110 | railties (= 5.1.6)
111 | sprockets-rails (>= 2.0.0)
112 | rails-dom-testing (2.0.3)
113 | activesupport (>= 4.2.0)
114 | nokogiri (>= 1.6)
115 | rails-html-sanitizer (1.0.4)
116 | loofah (~> 2.2, >= 2.2.2)
117 | railties (5.1.6)
118 | actionpack (= 5.1.6)
119 | activesupport (= 5.1.6)
120 | method_source
121 | rake (>= 0.8.7)
122 | thor (>= 0.18.1, < 2.0)
123 | rake (12.3.1)
124 | rb-fsevent (0.10.3)
125 | rb-inotify (0.9.10)
126 | ffi (>= 0.5.0, < 2)
127 | rspec-core (3.8.0)
128 | rspec-support (~> 3.8.0)
129 | rspec-expectations (3.8.1)
130 | diff-lcs (>= 1.2.0, < 2.0)
131 | rspec-support (~> 3.8.0)
132 | rspec-mocks (3.8.0)
133 | diff-lcs (>= 1.2.0, < 2.0)
134 | rspec-support (~> 3.8.0)
135 | rspec-rails (3.8.0)
136 | actionpack (>= 3.0)
137 | activesupport (>= 3.0)
138 | railties (>= 3.0)
139 | rspec-core (~> 3.8.0)
140 | rspec-expectations (~> 3.8.0)
141 | rspec-mocks (~> 3.8.0)
142 | rspec-support (~> 3.8.0)
143 | rspec-support (3.8.0)
144 | sass (3.5.7)
145 | sass-listen (~> 4.0.0)
146 | sass-listen (4.0.0)
147 | rb-fsevent (~> 0.9, >= 0.9.4)
148 | rb-inotify (~> 0.9, >= 0.9.7)
149 | sass-rails (5.0.7)
150 | railties (>= 4.0.0, < 6)
151 | sass (~> 3.1)
152 | sprockets (>= 2.8, < 4.0)
153 | sprockets-rails (>= 2.0, < 4.0)
154 | tilt (>= 1.1, < 3)
155 | spring (2.0.2)
156 | activesupport (>= 4.2)
157 | spring-watcher-listen (2.0.1)
158 | listen (>= 2.7, < 4.0)
159 | spring (>= 1.2, < 3.0)
160 | sprockets (3.7.2)
161 | concurrent-ruby (~> 1.0)
162 | rack (> 1, < 3)
163 | sprockets-rails (3.2.1)
164 | actionpack (>= 4.0)
165 | activesupport (>= 4.0)
166 | sprockets (>= 3.0.0)
167 | sqlite3 (1.3.13)
168 | thor (0.20.0)
169 | thread_safe (0.3.6)
170 | tilt (2.0.8)
171 | turbolinks (5.1.1)
172 | turbolinks-source (~> 5.1)
173 | turbolinks-source (5.1.0)
174 | tzinfo (1.2.5)
175 | thread_safe (~> 0.1)
176 | uglifier (4.1.18)
177 | execjs (>= 0.3.0, < 3)
178 | web-console (3.6.2)
179 | actionview (>= 5.0)
180 | activemodel (>= 5.0)
181 | bindex (>= 0.4.0)
182 | railties (>= 5.0)
183 | websocket-driver (0.6.5)
184 | websocket-extensions (>= 0.1.0)
185 | websocket-extensions (0.1.3)
186 | woothee (1.8.0)
187 |
188 | PLATFORMS
189 | ruby
190 |
191 | DEPENDENCIES
192 | byebug
193 | coffee-rails (~> 4.2)
194 | fluent-logger
195 | jbuilder (~> 2.5)
196 | jquery-rails
197 | listen (~> 3.0.5)
198 | puma (~> 3.0)
199 | rack-action_logger!
200 | rails (~> 5.1.0)
201 | rspec-rails
202 | sass-rails (~> 5.0)
203 | spring
204 | spring-watcher-listen (~> 2.0.0)
205 | sqlite3
206 | turbolinks (~> 5)
207 | tzinfo-data
208 | uglifier (>= 1.3.0)
209 | web-console
210 |
211 | BUNDLED WITH
212 | 1.16.3
213 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Rack::ActionLogger
2 |
3 | [](https://gitter.im/wapa5pow/rack-action_logger?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
4 |
5 | [](https://circleci.com/gh/wapa5pow/rack-action_logger)
6 | [](https://badge.fury.io/rb/rack-action_logger)
7 | [](https://codeclimate.com/github/wapa5pow/rack-action_logger)
8 | [](https://codeclimate.com/github/wapa5pow/rack-action_logger/coverage)
9 |
10 | **Rack::ActionLogger** is a tool to collect user action logs via fluentd, Rails.logger or any custome logger.
11 |
12 | It is intended to collect user request log, action log and any other custome logs.
13 |
14 | **Rails 5.1 or above** is required to use it. If you want to use it with other than these versions, please use 0.3.0
15 |
16 | ## Sample Logs
17 |
18 | ### Request log
19 |
20 | ```json
21 | {
22 | "message": {
23 | "path": "/",
24 | "method": "GET",
25 | "params": {
26 | "password": "[FILTERED]"
27 | },
28 | "request_headers": {
29 | "HTTP_VERSION": "HTTP/1.1",
30 | "HTTP_HOST": "localhost:3000",
31 | "HTTP_CONNECTION": "keep-alive",
32 | "HTTP_UPGRADE_INSECURE_REQUESTS": "1",
33 | "HTTP_USER_AGENT": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36",
34 | "HTTP_ACCEPT": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
35 | "HTTP_ACCEPT_ENCODING": "gzip, deflate, sdch, br",
36 | "HTTP_ACCEPT_LANGUAGE": "ja,en-US;q=0.8,en;q=0.6",
37 | "HTTP_COOKIE": "xxx"
38 | },
39 | "status_code": 200,
40 | "ip": "127.0.0.1",
41 | "remote_ip": "127.0.0.1",
42 | "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36",
43 | "device": "pc",
44 | "os": "Mac OSX",
45 | "browser": "Chrome",
46 | "browser_version": "54.0.2840.98",
47 | "request_id": "150a6ac9-0fd9-4a23-a313-d18da1e35911",
48 | "response_headers": {
49 | "X-Frame-Options": "SAMEORIGIN",
50 | "X-XSS-Protection": "1; mode=block",
51 | "X-Content-Type-Options": "nosniff",
52 | "Content-Type": "text/html; charset=utf-8"
53 | },
54 | "response_json_body": {
55 | },
56 | "tag": "action.rack",
57 | "user_id": 123
58 | }
59 | }
60 | ```
61 |
62 | ### Append log
63 |
64 | ```json
65 | {
66 | "message": {
67 | "request_id": "150a6ac9-0fd9-4a23-a313-d18da1e35911",
68 | "value": "with_tag",
69 | "tag": "action.activities"
70 | }
71 | }
72 | ```
73 |
74 | Under example folder, there are sample Rails applications to see how these sample logs are created.
75 |
76 | ### Model log
77 |
78 | ```json
79 | {
80 | "message": {
81 | "user_id": null,
82 | "request_id": "5aae4cc6-125b-4049-b555-502d6968e041",
83 | "_method": "update",
84 | "_after:updated_at": "2016-11-18 18:40:15 +0900",
85 | "_before:updated_at": "2016-11-18 18:33:56 +0900",
86 | "_after:views": 96,
87 | "_before:views": 95,
88 | "tag": "action.model_articles"
89 | },
90 | "tag": "action.model_articles"
91 | }
92 | ```
93 |
94 | ## Installation
95 |
96 | Add this line to your rails application's Gemfile:
97 |
98 | ```ruby
99 | gem 'rack-action_logger'
100 | gem 'fluent-logger'
101 | ```
102 |
103 | And then execute:
104 |
105 | ```
106 | bundle
107 | ```
108 |
109 | Then, add Rack::ActionLogger as middleware to config/application.rb.
110 |
111 | ```ruby
112 | config.middleware.use Rack::ActionLogger
113 | ```
114 |
115 | ### Setup Initializations
116 |
117 | Under config/initializers, add the following files.
118 |
119 | #### fluent_logger.rb
120 |
121 | ```ruby
122 | Fluent::Logger::FluentLogger.open
123 | ```
124 |
125 | #### rack-action_logger.rb
126 |
127 | ```ruby
128 | Rack::ActionLogger.configure do |config|
129 | config.emit_adapter = Rack::ActionLogger::EmitAdapter::FluentAdapter
130 | config.wrap_key = :message
131 | config.logger = Rails.logger
132 | config.filters = Rails.application.config.filter_parameters
133 | end
134 | ```
135 |
136 | If wrap_key is nil, the out put does not have parent key of wrap_key.
137 |
138 | ## Usage
139 |
140 | ### Enable Request Log
141 |
142 | Request log is automatically enabled
143 |
144 | Request can be customized by creating new class for rack_metrics configuration.
145 |
146 | ### Add Append Log
147 |
148 | Add the following code to any code on any times.
149 |
150 | ```ruby
151 | Rack::ActionLogger::Container.add_append_log({ value: 'ok' }, 'activities')
152 | ```
153 |
154 | ### Add Model Logger
155 |
156 | Add the folloing line to ```config/initializers/rack-action_logger.rb``` at the end of line.
157 |
158 | ```
159 | ActiveRecord::Base.send(:include, Rack::ActionLogger::ActiveRecordExtension)
160 | ```
161 |
162 | ### Override log attributes
163 |
164 | Overriden attributes are added to both request and append logs.
165 |
166 | ```ruby
167 | Rack::ActionLogger::Container.merge_attributes({ user_id: 123 })
168 | ```
169 |
170 | The append log is overrided by user_id attribute.
171 |
172 | ```json
173 | {
174 | "message": {
175 | "request_id": "150a6ac9-0fd9-4a23-a313-d18da1e35911",
176 | "value": "with_tag",
177 | "uer_id": 123,
178 | "tag": "action.activities"
179 | }
180 | }
181 | ```
182 |
183 | ### Logs out of request
184 |
185 | If Rails app uses background job system like sidekiq, exported context (e.g. log attributes and request_id) can be passed to the job.
186 |
187 | For example, a worker is the following.
188 |
189 | ```ruby
190 | class TestWorker < ApplicationController
191 | include Sidekiq::Worker
192 | sidekiq_options queue: :test, retry: 5
193 |
194 | def perform(title, context)
195 | Rack::ActionLogger::Emitter.new.emit(context) do
196 | Rack::ActionLogger::Container.add_append_log({ title: title }, 'worker')
197 | p 'work: title=' + title
198 | end
199 | end
200 |
201 | end
202 | ```
203 |
204 | To call the worker task, the app should call like the following.
205 |
206 | ```ruby
207 | action_log_context = Rack::ActionLogger::Container.export
208 | TestWorker.perform_async('Worker Job', action_log_context)
209 | ```
210 |
211 | ## Development
212 |
213 | After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
214 |
215 | To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
216 |
217 | ## Contributing
218 |
219 | Bug reports and pull requests are welcome on GitHub at https://github.com/wapa5pow/rack-action_logger. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
220 |
221 |
222 | ## License
223 |
224 | The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
225 |
226 |
--------------------------------------------------------------------------------