civo-logger 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 9ea141cbe943479a4513bc25a1dc51f349f9666f
4
+ data.tar.gz: a2295ac14d004893970e7ad4fce4e00843126c42
5
+ SHA512:
6
+ metadata.gz: 305e441d35258126e63e5f7fc0fb59fe3f29247b1d7610263dfa36c346d1af99313d6c658f5119f24eeda6b542d61e7d727f40600e02e58bc0eb3ac52c728a50
7
+ data.tar.gz: 043ca6f44b552b345dd4a0c0d64725bfdcec8acde302eb03048637cef97cf7180dfc161d40c2a53e14187386fc9ec9d509101fd5f77452abc09cb91896918896
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.3.3
5
+ before_install: gem install bundler -v 1.14.6
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in civo-logger.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Andy Jeffries
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.
data/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # Civo::Logger
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/civo/logger`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'civo-logger'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install civo-logger
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ 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.
30
+
31
+ 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).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/andyjeffries/civo-logger.
36
+
37
+
38
+ ## License
39
+
40
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
41
+
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "civo/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(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
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
@@ -0,0 +1,27 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'civo/logger/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "civo-logger"
8
+ spec.version = Civo::Logger::VERSION
9
+ spec.authors = ["Andy Jeffries"]
10
+ spec.email = ["hello@civo.com"]
11
+
12
+ spec.summary = %q{A per-request logger}
13
+ spec.description = %q{Sends each request individually to Redis}
14
+ spec.homepage = "https://www.civo.com"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_development_dependency "bundler", "~> 1.14"
25
+ spec.add_development_dependency "rake", "~> 10.0"
26
+ spec.add_development_dependency "rspec", "~> 3.0"
27
+ end
@@ -0,0 +1,8 @@
1
+ require "civo/logger/version"
2
+ require "civo/logger/middleware"
3
+
4
+ module Civo
5
+ module Logger
6
+ # Your code goes here...
7
+ end
8
+ end
@@ -0,0 +1,222 @@
1
+ require "active_support/core_ext/time/conversions"
2
+ require "active_support/core_ext/object/blank"
3
+ require "active_support/log_subscriber"
4
+ require "action_dispatch/http/request"
5
+ require "rack/body_proxy"
6
+
7
+ module Civo
8
+ class PerRequestLogger < ActiveSupport::LogSubscriber
9
+ STATS_RESOLUTION = 5.minutes
10
+
11
+ def initialize(app, taggers = nil)
12
+ @app = app
13
+ @taggers = taggers || []
14
+ Rails.logger = ActionController::Base.logger = ActiveRecord::Base.logger = self
15
+ $stdout.sync = true
16
+ if ENV["RAILS_LOGGER_HOSTNAME"].present?
17
+ puts "Setting REDIS to the remote one"
18
+ @redis = Redis.new(host: ENV["RAILS_LOGGER_HOSTNAME"], port: Rails.application.config.x.redis_port, password: ENV["RAILS_LOGGER_PASSWORD"])
19
+ else
20
+ @redis = Redis.current
21
+ end
22
+ end
23
+
24
+ def call(env)
25
+ request = ActionDispatch::Request.new(env)
26
+
27
+ call_app(request, env)
28
+ end
29
+
30
+ def debug(message = "")
31
+ message = yield if block_given?
32
+ return if message.blank?
33
+ @lines << message if debug? && @recording
34
+ end
35
+
36
+ def debug?
37
+ %i{debug}.include?(level)
38
+ end
39
+
40
+ def info(message = "")
41
+ message = yield if block_given?
42
+ return if message.blank?
43
+
44
+ matches = message.match(/Completed (\d+) .*? in (\d+)ms/)
45
+ if matches
46
+ @status = matches[1]
47
+ @time_taken = matches[2]
48
+ end
49
+ @lines << message if info? && @recording
50
+ end
51
+
52
+ def info?
53
+ %i{debug info}.include?(level)
54
+ end
55
+
56
+ def warn(message = "")
57
+ message = yield if block_given?
58
+ return if message.blank?
59
+ @lines << message if warn? && @recording
60
+ end
61
+
62
+ def warn?
63
+ %i{debug info warn}.include?(level)
64
+ end
65
+
66
+ def error(message = "")
67
+ message = yield if block_given?
68
+ return if message.blank?
69
+ @lines << message if error? && @recording
70
+ end
71
+
72
+ def error?
73
+ %i{debug info warn error}.include?(level)
74
+ end
75
+
76
+ def fatal(message = "")
77
+ message = yield if block_given?
78
+ return if message.blank?
79
+ @lines << message if fatal? && @recording
80
+ end
81
+
82
+ def fatal?
83
+ %i{debug info warn error fatal}.include?(level)
84
+ end
85
+
86
+ def level
87
+ Rails.configuration.log_level
88
+ end
89
+
90
+ def formatter
91
+ ActiveSupport::Logger::SimpleFormatter
92
+ end
93
+
94
+ def start_worker(name)
95
+ @name = name
96
+ @key = Time.zone.now.strftime("%Y%m%d-%H%I%S")+"-#{name}"
97
+ @lines = []
98
+ @start = Time.now.to_f
99
+ @recording = true
100
+ end
101
+
102
+ def end_worker
103
+ @redis.set("civo-api:log:#{@key}", @lines.join("\n"), expires_in: 1.hour)
104
+ puts @lines.join("\n") if Rails.env.production?
105
+ @recording = false
106
+ end
107
+
108
+ private
109
+
110
+ def request_key(request)
111
+ token = rand(8999) + 1000
112
+ @key = Time.zone.now.strftime("%Y%m%d-%H%I%S") +
113
+ "-#{token}-#{request.request_method}-#{request.fullpath.gsub("/", "_")}".strip
114
+ end
115
+
116
+ def call_app(request, env) # :doc:
117
+ @lines = []
118
+ @recording = true
119
+ @status = nil
120
+ @time_taken = nil
121
+ @key = request_key(request)
122
+ Rails.logger = ActionController::Base.logger = ActiveRecord::Base.logger = self
123
+ instrumenter = ActiveSupport::Notifications.instrumenter
124
+ instrumenter.start "request.action_dispatch", request: request
125
+ logger.info { started_request_message(request) }
126
+ resp = @app.call(env)
127
+ puts "HELLO!"
128
+ resp[2] = ::Rack::BodyProxy.new(resp[2]) { finish(request, resp[2]) }
129
+ resp
130
+ rescue Exception
131
+ finish(request, "")
132
+ raise
133
+ ensure
134
+ ActiveSupport::LogSubscriber.flush_all!
135
+ end
136
+
137
+ # Started GET "/session/new" for 127.0.0.1 at 2012-09-26 14:51:42 -0700
138
+ def started_request_message(request) # :doc:
139
+ 'Started %s "%s" for %s at %s' % [
140
+ request.request_method,
141
+ request.filtered_path,
142
+ request.ip,
143
+ Time.now.to_default_s ]
144
+ end
145
+
146
+ def compute_tags(request) # :doc:
147
+ @taggers.collect do |tag|
148
+ case tag
149
+ when Proc
150
+ tag.call(request)
151
+ when Symbol
152
+ request.send(tag)
153
+ else
154
+ tag
155
+ end
156
+ end
157
+ end
158
+
159
+ def finish(request, body = "")
160
+ instrumenter = ActiveSupport::Notifications.instrumenter
161
+ instrumenter.finish "request.action_dispatch", request: request
162
+ @log = @lines.join("\n")
163
+
164
+ if body.respond_to?(:each)
165
+ @output = []
166
+ body.each do |line|
167
+ @output << line
168
+ end
169
+ @output = @output.join("\n")
170
+ else
171
+ @output = body
172
+ end
173
+
174
+ puts "Should I send it? #{send_request?(request)}"
175
+ if send_request?(request)
176
+ puts "Sending... to #{@redis.inspect}"
177
+ @redis.set("civo-api:log:#{@key}", @log[0, 65535], expires_in: 1.hour)
178
+ @redis.set("civo-api:log-output:#{@key}", @output, expires_in: 1.hour)
179
+ puts "Yes, done!"
180
+
181
+ puts "#{request.request_method}-#{request.fullpath.gsub("/", "_")}-#{@output.length}-#{@status}-#{@time_taken}" if Rails.env.production?
182
+
183
+ @redis.set("civo-api:log-request-summary:#{@key}",
184
+ "#{request.request_method}:#{request.fullpath.gsub("/", "_")}:#{@output.length}:#{@status}:#{@time_taken}", expires_in: 1.hour)
185
+ puts @log if Rails.env.production?
186
+
187
+ stat_key = Time.zone.at(Time.zone.now.to_i / STATS_RESOLUTION * STATS_RESOLUTION).strftime("%Y%m%d-%H%I%S")
188
+ if @status.to_i > 399
189
+ @redis.incr("civo-api:req-stat-failure:#{stat_key}")
190
+ @redis.expire("civo-api:req-stat-failure:#{stat_key}", 7.days)
191
+ else
192
+ @redis.incr("civo-api:req-stat-success:#{stat_key}")
193
+ @redis.expire("civo-api:req-stat-success:#{stat_key}", 7.days)
194
+ end
195
+ end
196
+
197
+ if Rails.env.development? || Rails.env.test?
198
+ File.open("#{Rails.root}/log/#{Rails.env}.log", "a") do |f|
199
+ f << @log
200
+ end
201
+ end
202
+
203
+ @recording = false
204
+ end
205
+
206
+ def send_request?(request)
207
+ if request.fullpath["/resque"]
208
+ return false
209
+ elsif request.fullpath["/civostatsd"]
210
+ return false
211
+ elsif request.fullpath["/ping"]
212
+ return false
213
+ end
214
+
215
+ true
216
+ end
217
+
218
+ def logger
219
+ self
220
+ end
221
+ end
222
+ end
@@ -0,0 +1,5 @@
1
+ module Civo
2
+ module Logger
3
+ VERSION = "0.1.0"
4
+ end
5
+ end
metadata ADDED
@@ -0,0 +1,99 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: civo-logger
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Andy Jeffries
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-11-06 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.14'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.14'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ description: Sends each request individually to Redis
56
+ email:
57
+ - hello@civo.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - ".rspec"
64
+ - ".travis.yml"
65
+ - Gemfile
66
+ - LICENSE.txt
67
+ - README.md
68
+ - Rakefile
69
+ - bin/console
70
+ - bin/setup
71
+ - civo-logger.gemspec
72
+ - lib/civo/logger.rb
73
+ - lib/civo/logger/middleware.rb
74
+ - lib/civo/logger/version.rb
75
+ homepage: https://www.civo.com
76
+ licenses:
77
+ - MIT
78
+ metadata: {}
79
+ post_install_message:
80
+ rdoc_options: []
81
+ require_paths:
82
+ - lib
83
+ required_ruby_version: !ruby/object:Gem::Requirement
84
+ requirements:
85
+ - - ">="
86
+ - !ruby/object:Gem::Version
87
+ version: '0'
88
+ required_rubygems_version: !ruby/object:Gem::Requirement
89
+ requirements:
90
+ - - ">="
91
+ - !ruby/object:Gem::Version
92
+ version: '0'
93
+ requirements: []
94
+ rubyforge_project:
95
+ rubygems_version: 2.6.13
96
+ signing_key:
97
+ specification_version: 4
98
+ summary: A per-request logger
99
+ test_files: []