pier_logging 0.1.2

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.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0a2b1c76716abf96ce6ed1d392d3ac945a3565b05abb16f5400fd1f41a27e509
4
+ data.tar.gz: 22ab7775f0c76d51075d566b7d8561c8ceed631693661ef6995669f03c51a809
5
+ SHA512:
6
+ metadata.gz: 54864d9541a7aecb5e470d00b8938d3f1198ffb031ecb7057e2b4bcbe00bf5e3f5f7f953fa39f927071f4d26cf0f8a7c1c1d07f68c0bcee66edaf6700b7597e1
7
+ data.tar.gz: 5a2230fcf76ac2e0563b9100f90f6841b0c97a1cf907b8e6e017fc65934f92201a1ef8cc64becbf309caf5efcf03a83fd3d5444263c74fe10c244c3e73b5d629
@@ -0,0 +1,51 @@
1
+ name: Publish gem
2
+
3
+ on:
4
+ push:
5
+ branches: [ master ]
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - name: Checkout code
12
+ uses: actions/checkout@v2.1.0
13
+ - name: Check if version changed
14
+ uses: tony84727/changed-file-filter@0.0.2
15
+ id: filter
16
+ with:
17
+ filters: |
18
+ version:
19
+ - 'lib/pier_logging/version.rb'
20
+ - name: Setup Ruby
21
+ # if: steps.filter.outputs.version == 'true'
22
+ uses: ruby/setup-ruby@v1
23
+ with:
24
+ ruby-version: 2.7.1
25
+ - name: Get version
26
+ # if: steps.filter.outputs.version == 'true'
27
+ id: new_version
28
+ run: echo "##[set-output name=version;]$(ruby ./bin/get_current_version.rb)"
29
+ - name: Create tag
30
+ uses: tvdias/github-tagger@v0.0.1
31
+ with:
32
+ repo-token: "${{ secrets.GITHUB_TOKEN }}"
33
+ tag: "${{ steps.new_version.outputs.version }}"
34
+ - name: Create Release
35
+ # if: steps.filter.outputs.version == 'true'
36
+ id: create_release
37
+ uses: actions/create-release@v1
38
+ env:
39
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
40
+ with:
41
+ tag_name: ${{ steps.new_version.outputs.version }}
42
+ release_name: Release ${{ steps.new_version.outputs.version }}
43
+ tag_prefix: v
44
+ draft: false
45
+ prerelease: false
46
+ - name: Publish Gem
47
+ # if: steps.filter.outputs.version == 'true'
48
+ env:
49
+ VERSION: ${{ steps.new_version.outputs.version }}
50
+ RUBYGEMS_API_KEY: ${{ secrets.RUBYGEMS_API_KEY }}
51
+ run: ruby ./bin/publish_gem.rb
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ *.gem
@@ -0,0 +1 @@
1
+ 2.7.1
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.3
7
+ before_install: gem install bundler -v 1.17.2
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in pier_logging.gemspec
6
+ gemspec
@@ -0,0 +1,152 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ pier_logging (0.1.2)
5
+ awesome_print
6
+ ougai
7
+ rails
8
+
9
+ GEM
10
+ remote: https://rubygems.org/
11
+ specs:
12
+ actioncable (6.0.3.2)
13
+ actionpack (= 6.0.3.2)
14
+ nio4r (~> 2.0)
15
+ websocket-driver (>= 0.6.1)
16
+ actionmailbox (6.0.3.2)
17
+ actionpack (= 6.0.3.2)
18
+ activejob (= 6.0.3.2)
19
+ activerecord (= 6.0.3.2)
20
+ activestorage (= 6.0.3.2)
21
+ activesupport (= 6.0.3.2)
22
+ mail (>= 2.7.1)
23
+ actionmailer (6.0.3.2)
24
+ actionpack (= 6.0.3.2)
25
+ actionview (= 6.0.3.2)
26
+ activejob (= 6.0.3.2)
27
+ mail (~> 2.5, >= 2.5.4)
28
+ rails-dom-testing (~> 2.0)
29
+ actionpack (6.0.3.2)
30
+ actionview (= 6.0.3.2)
31
+ activesupport (= 6.0.3.2)
32
+ rack (~> 2.0, >= 2.0.8)
33
+ rack-test (>= 0.6.3)
34
+ rails-dom-testing (~> 2.0)
35
+ rails-html-sanitizer (~> 1.0, >= 1.2.0)
36
+ actiontext (6.0.3.2)
37
+ actionpack (= 6.0.3.2)
38
+ activerecord (= 6.0.3.2)
39
+ activestorage (= 6.0.3.2)
40
+ activesupport (= 6.0.3.2)
41
+ nokogiri (>= 1.8.5)
42
+ actionview (6.0.3.2)
43
+ activesupport (= 6.0.3.2)
44
+ builder (~> 3.1)
45
+ erubi (~> 1.4)
46
+ rails-dom-testing (~> 2.0)
47
+ rails-html-sanitizer (~> 1.1, >= 1.2.0)
48
+ activejob (6.0.3.2)
49
+ activesupport (= 6.0.3.2)
50
+ globalid (>= 0.3.6)
51
+ activemodel (6.0.3.2)
52
+ activesupport (= 6.0.3.2)
53
+ activerecord (6.0.3.2)
54
+ activemodel (= 6.0.3.2)
55
+ activesupport (= 6.0.3.2)
56
+ activestorage (6.0.3.2)
57
+ actionpack (= 6.0.3.2)
58
+ activejob (= 6.0.3.2)
59
+ activerecord (= 6.0.3.2)
60
+ marcel (~> 0.3.1)
61
+ activesupport (6.0.3.2)
62
+ concurrent-ruby (~> 1.0, >= 1.0.2)
63
+ i18n (>= 0.7, < 2)
64
+ minitest (~> 5.1)
65
+ tzinfo (~> 1.1)
66
+ zeitwerk (~> 2.2, >= 2.2.2)
67
+ awesome_print (1.8.0)
68
+ builder (3.2.4)
69
+ byebug (11.1.3)
70
+ concurrent-ruby (1.1.6)
71
+ crass (1.0.6)
72
+ erubi (1.9.0)
73
+ globalid (0.4.2)
74
+ activesupport (>= 4.2.0)
75
+ i18n (1.8.3)
76
+ concurrent-ruby (~> 1.0)
77
+ loofah (2.6.0)
78
+ crass (~> 1.0.2)
79
+ nokogiri (>= 1.5.9)
80
+ mail (2.7.1)
81
+ mini_mime (>= 0.1.1)
82
+ marcel (0.3.3)
83
+ mimemagic (~> 0.3.2)
84
+ method_source (1.0.0)
85
+ mimemagic (0.3.5)
86
+ mini_mime (1.0.2)
87
+ mini_portile2 (2.4.0)
88
+ minitest (5.14.1)
89
+ nio4r (2.5.2)
90
+ nokogiri (1.10.9)
91
+ mini_portile2 (~> 2.4.0)
92
+ oj (3.10.6)
93
+ ougai (1.8.5)
94
+ oj (~> 3.10)
95
+ rack (2.2.3)
96
+ rack-test (1.1.0)
97
+ rack (>= 1.0, < 3)
98
+ rails (6.0.3.2)
99
+ actioncable (= 6.0.3.2)
100
+ actionmailbox (= 6.0.3.2)
101
+ actionmailer (= 6.0.3.2)
102
+ actionpack (= 6.0.3.2)
103
+ actiontext (= 6.0.3.2)
104
+ actionview (= 6.0.3.2)
105
+ activejob (= 6.0.3.2)
106
+ activemodel (= 6.0.3.2)
107
+ activerecord (= 6.0.3.2)
108
+ activestorage (= 6.0.3.2)
109
+ activesupport (= 6.0.3.2)
110
+ bundler (>= 1.3.0)
111
+ railties (= 6.0.3.2)
112
+ sprockets-rails (>= 2.0.0)
113
+ rails-dom-testing (2.0.3)
114
+ activesupport (>= 4.2.0)
115
+ nokogiri (>= 1.6)
116
+ rails-html-sanitizer (1.3.0)
117
+ loofah (~> 2.3)
118
+ railties (6.0.3.2)
119
+ actionpack (= 6.0.3.2)
120
+ activesupport (= 6.0.3.2)
121
+ method_source
122
+ rake (>= 0.8.7)
123
+ thor (>= 0.20.3, < 2.0)
124
+ rake (13.0.1)
125
+ sprockets (4.0.2)
126
+ concurrent-ruby (~> 1.0)
127
+ rack (> 1, < 3)
128
+ sprockets-rails (3.2.1)
129
+ actionpack (>= 4.0)
130
+ activesupport (>= 4.0)
131
+ sprockets (>= 3.0.0)
132
+ thor (1.0.1)
133
+ thread_safe (0.3.6)
134
+ tzinfo (1.2.7)
135
+ thread_safe (~> 0.1)
136
+ websocket-driver (0.7.2)
137
+ websocket-extensions (>= 0.1.0)
138
+ websocket-extensions (0.1.5)
139
+ zeitwerk (2.3.1)
140
+
141
+ PLATFORMS
142
+ ruby
143
+
144
+ DEPENDENCIES
145
+ bundler (>= 2.1.4)
146
+ byebug (>= 11.1.3)
147
+ minitest (>= 5.8.4)
148
+ pier_logging!
149
+ rake (>= 12.3.3)
150
+
151
+ BUNDLED WITH
152
+ 2.1.4
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 Mauricio Banduk
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.
@@ -0,0 +1,39 @@
1
+ # PierLogging
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/pier_logging`. 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 'pier_logging'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install pier_logging
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 test` 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/[USERNAME]/pier_logging.
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList["test/**/*_test.rb"]
8
+ end
9
+
10
+ task :default => :test
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "pier_logging"
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__)
@@ -0,0 +1 @@
1
+ print Gem::Specification::load('pier_logging.gemspec').version.to_s
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env bash
2
+
3
+ # ==================================================================================================
4
+ # Required preset env vars
5
+ # ==================================================================================================
6
+ # SLACK_WEBHOOK:
7
+ # The Slack webhook url
8
+ # Reference: https://slack.com/apps/A0F7XDUAZ-incoming-webhooks
9
+ # Please use github secrets to store it
10
+ # SLACK_CHANNEL:
11
+ # The slack channel to send message to
12
+ # How to get: https://stackoverflow.com/a/44883343/536807
13
+ # Please use github secrets to store it
14
+ # STATUS:
15
+ # The github action job status
16
+ # You can get this with `${{ job.status }}`
17
+ # GH_REPO:
18
+ # The github repository
19
+ # You can get this with `${{ github.repository }}`
20
+ # GH_MESSAGE:
21
+ # The commit message of the commit to show as code block in the slack message
22
+ # You can get this with `${{ github.event.commits[0].message }}`
23
+ # GH_ACTOR:
24
+ # The person to show as the responsible for the commit
25
+ # You can get this with `${{ github.actor }}`
26
+ # GH_SHA:
27
+ # The sha of the commit
28
+ # You can get this with `${{ github.sha }}``
29
+ # APP_ENVIRONMENT:
30
+ # The application environment, usually `production` or `staging`
31
+ # DEPLOY_TARGET:
32
+ # Where it was deployed to, usually a heroku app name
33
+ # LANGUAGE:
34
+ # The main programming language of the project. This is used to show the language
35
+ # icon on the slack message. We use a bitbucket CDN to get the images. Please test
36
+ # the image exists before setting it
37
+ # Known working values: `ruby`, `python`, `nodejs`
38
+
39
+ REPO_NAME=`cut -d "/" -f2 <<< "$GH_REPO"`
40
+ NOW=`date +'%s'`
41
+ FOOTER_ICON="https://d301sr5gafysq2.cloudfront.net/e0aa900cf99a/img/repo-avatars/$LANGUAGE.png"
42
+ USERNAME="Github"
43
+ TEXT="\`\`\`$GH_MESSAGE\`\`\`"
44
+ TITLE_LINK="https://github.com/$GH_REPO/commit/$GH_SHA/checks"
45
+ AUTHOR_NAME="$GH_ACTOR"
46
+ AUTHOR_ICON="http://github.com/$GH_ACTOR.png?size=32"
47
+ AUTHOR_LINK="http://github.com/$GH_ACTOR"
48
+ STATUS=`echo $STATUS | tr '[A-Z]' '[a-z]'`
49
+
50
+ if [ "$STATUS" = "success" ]
51
+ then
52
+ ICON_EMOJI=":ivete-happy:"
53
+ NOTIFICATION_COLOR="#5DB182"
54
+ elif [ "$STATUS" = "failure" ]
55
+ then
56
+ ICON_EMOJI=":ivete-sad:"
57
+ NOTIFICATION_COLOR="#EC6240"
58
+ else
59
+ ICON_EMOJI=":ivete:"
60
+ NOTIFICATION_COLOR="#CCCCCC"
61
+ fi
62
+
63
+ read -r -d '' body << EOF
64
+ {
65
+ "channel": "$SLACK_CHANNEL",
66
+ "username": "$USERNAME",
67
+ "icon_emoji": "$ICON_EMOJI",
68
+ "attachments": [
69
+ {
70
+ "color": "$NOTIFICATION_COLOR",
71
+ "title": "[$REPO_NAME] Deploy to $APP_ENVIRONMENT",
72
+ "text": "$TEXT",
73
+ "title_link": "$TITLE_LINK",
74
+ "fallback": "[$REPO_NAME] Successfully deployed to $APP_ENVIRONMENT",
75
+ "author_name": "$AUTHOR_NAME",
76
+ "author_icon": "$AUTHOR_ICON",
77
+ "author_link": "$AUTHOR_LINK",
78
+ "ts": $NOW,
79
+ "footer_icon": "$FOOTER_ICON",
80
+ "footer": "$REPO_NAME",
81
+ "fields": [
82
+ { "title": "Status", "value": "$STATUS", "short": true },
83
+ { "title": "Deployed to", "value": "$DEPLOY_TARGET", "short": true }
84
+ ]
85
+ }
86
+ ]
87
+ }
88
+ EOF
89
+
90
+ curl "$SLACK_WEBHOOK" \
91
+ -X POST \
92
+ -H "Content-type: application/json; charset=utf-8" \
93
+ -d "$body"
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'fileutils'
5
+
6
+ def safe_system(*cmd)
7
+ exit 1 unless system(*cmd)
8
+ end
9
+
10
+ api_key = ENV['RUBYGEMS_API_KEY'] || 'dummy'
11
+ gemspec_files = Dir.glob('*.gemspec')
12
+ credentials_dir_path = "#{Dir.home}/.gem"
13
+ credentials_file_path = "#{credentials_dir_path}/credentials"
14
+ credentials = <<~END_OF_CREDENTIALS
15
+ ---
16
+ :rubygems_api_key: #{api_key}
17
+ END_OF_CREDENTIALS
18
+
19
+ FileUtils.mkdir_p(credentials_dir_path)
20
+ File.open(credentials_file_path, 'w') { |f| f.write(credentials) }
21
+ FileUtils.chmod(0o600, credentials_file_path)
22
+
23
+ gemspec_files.each do |gemspec_file|
24
+ gemspec = Gem::Specification.load(gemspec_file)
25
+ gem_file = gemspec.full_name + '.gem'
26
+ safe_system('gem', 'build', gemspec_file)
27
+ safe_system('gem', 'push', gem_file)
28
+ end
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ echo "Checking changed files"
3
+ files=$(git diff --name-only origin/master -- | xargs ls -d 2>/dev/null | egrep "\.(rb|spec|rake|rhtml|rjs|rxml|erb)$")
4
+ echo "Changed files:"
5
+ echo "***"
6
+ echo "$files"
7
+ echo "***"
8
+ if [ -z "$files" ]; then echo "No ruby files were changed"; else echo "$files" | xargs rubocop -l ; fi
@@ -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,69 @@
1
+ require "rails"
2
+ require "ougai"
3
+ require "pier_logging/version"
4
+ require "pier_logging/logger"
5
+ require "pier_logging/request_logger"
6
+ require "pier_logging/formatter/base"
7
+ require "pier_logging/formatter/json"
8
+ require "pier_logging/formatter/readable"
9
+
10
+ module PierLogging
11
+ def self.logger_configuration
12
+ @logger_configuration ||= LoggerConfiguration.new
13
+ end
14
+
15
+ def self.configure_logger
16
+ yield(logger_configuration)
17
+ end
18
+
19
+ def self.request_logger_configuration
20
+ @request_logger_configuration ||= RequestLoggerConfiguration.new
21
+ end
22
+
23
+ def self.configure_request_logger
24
+ yield(request_logger_configuration)
25
+ end
26
+
27
+ class LoggerConfiguration
28
+ attr_reader :app_name, :env, :formatter
29
+
30
+ def initialize
31
+ @app_name = nil
32
+ @env = nil
33
+ @formatter = Formatter::Json.new
34
+ end
35
+
36
+ def app_name=(app_name)
37
+ raise ArgumentError, "Config 'app_name' must be a String" unless app_name.is_a?(String)
38
+ @app_name = app_name
39
+ end
40
+
41
+ def env=(env)
42
+ raise ArgumentError, "Config 'env' must be a String" unless env.is_a?(String)
43
+ @env = env
44
+ end
45
+
46
+ def formatter=(formatter)
47
+ raise ArgumentError, "Config 'formatter' must be a 'Ougai::Formatters::Base'" unless formatter.is_a?(Ougai::Formatters::Base)
48
+ @formatter = formatter
49
+ end
50
+ end
51
+
52
+ class RequestLoggerConfiguration
53
+ attr_reader :enabled, :user_info_getter
54
+
55
+ def initialize
56
+ @user_info_getter = nil
57
+ @enabled = false
58
+ end
59
+
60
+ def user_info_getter(&block)
61
+ raise ArgumentError, "Config 'user_info_getter' must be a 'Proc'" unless block_given?
62
+ @user_info_getter = block
63
+ end
64
+
65
+ def enabled=(enabled = false)
66
+ @enabled = enabled
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,48 @@
1
+
2
+ # The base formatter
3
+ module PierLogging
4
+ module Formatter
5
+ class Base < Ougai::Formatters::Base
6
+ include Ougai::Formatters::ForJson
7
+
8
+ def initialize(app_name = nil, hostname = nil, opts = {})
9
+ aname, hname, opts = Ougai::Formatters::Base.parse_new_params([app_name, hostname, opts])
10
+ super(aname, hname, opts)
11
+ end
12
+
13
+ def get_message(data)
14
+ # Use `message` (besides `msg` - ougai default) as the message field
15
+ if data.is_a?(Hash)
16
+ msg = data.delete(:msg)
17
+ data[:message] = msg if !data[:message]
18
+ end
19
+ data.delete(:message)
20
+ end
21
+
22
+ def get_message_type(data)
23
+ data.delete(:type) || 'default'
24
+ end
25
+
26
+ def get_log_content(severity, time, message, message_type, data)
27
+ dump({
28
+ env: PierLogging.logger_configuration.env,
29
+ app: PierLogging.logger_configuration.app_name,
30
+ level: severity.downcase,
31
+ timestamp: time,
32
+ message: message,
33
+ type: message_type,
34
+ }.merge({ fields: data }))
35
+ end
36
+
37
+ def _call(severity, time, progname, data)
38
+ message = get_message(data)
39
+ message_type = get_message_type(data)
40
+ get_log_content(severity, time, message, message_type, data)
41
+ end
42
+
43
+ def convert_time(data)
44
+ data[:timestamp] = data[:timestamp].utc.iso8601(3)
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,13 @@
1
+
2
+ # A JSON formatter
3
+ module PierLogging
4
+ module Formatter
5
+ class Json < Base
6
+ def initialize(app_name = nil, hostname = nil, opts = {})
7
+ aname, hname, opts = Ougai::Formatters::Base.parse_new_params([app_name, hostname, opts])
8
+ super(aname, hname, opts)
9
+ init_opts_for_json(opts)
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,10 @@
1
+ # A Readable formatter
2
+ module PierLogging
3
+ module Formatter
4
+ class Readable < Base
5
+ def get_log_content(severity, time, message, message_type, data)
6
+ super.ai
7
+ end
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,11 @@
1
+
2
+ module PierLogging
3
+ class Logger < Ougai::Logger
4
+ include ActiveSupport::LoggerThreadSafeLevel
5
+ include ActiveSupport::LoggerSilence
6
+
7
+ def create_formatter
8
+ PierLogging.logger_configuration.formatter
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,144 @@
1
+ # Requiring only the part that we need
2
+ require 'facets/hash/traverse'
3
+ module PierLogging
4
+ class RequestLogger
5
+ REDACT_REPLACE_KEYS = [
6
+ /passw(or)?d/i,
7
+ /^pw$/,
8
+ /^pass$/i,
9
+ /secret/i,
10
+ /token/i,
11
+ /api[-._]?key/i,
12
+ /session[-._]?id/i,
13
+ /^connect\.sid$/
14
+ ].freeze
15
+ REDACT_REPLACE_BY = '*'.freeze
16
+
17
+ attr_reader :logger
18
+
19
+ def initialize(app, logger = PierLogging::Logger.new(STDOUT))
20
+ @app = app
21
+ @logger = logger
22
+ end
23
+
24
+ def call(env)
25
+ starts_at = Time.now.utc
26
+ begin
27
+ status, type, body = response = @app.call(env)
28
+ log([env, status, type, body, starts_at, Time.now.utc, nil])
29
+ rescue Exception => exception
30
+ status = determine_status_code_from_exception(exception)
31
+ type = determine_type_from_exception(exception)
32
+ body = determine_body_from_exception(exception)
33
+ log([env, status, type, body, starts_at, Time.now.utc, exception])
34
+ raise exception
35
+ end
36
+
37
+ response
38
+ end
39
+
40
+ # Optimization https://github.com/JuanitoFatas/fast-ruby#function-with-single-array-argument-vs-splat-arguments-code
41
+ def log(args)
42
+ return unless PierLogging.request_logger_configuration.enabled
43
+
44
+ env, status, type, body, starts_at, ends_at, _ = args
45
+ request = Rack::Request.new(env)
46
+ request_headers = get_request_headers_from_env(env)
47
+ logger.info redact_hash({
48
+ message: build_message_from_request(request),
49
+ type: 'http',
50
+ duration: ((ends_at - starts_at)*1000).to_i,
51
+ context: {
52
+ user: get_user_info_from_headers(request_headers),
53
+ correlation_id: env['action_dispatch.request_id'],
54
+ },
55
+ request: {
56
+ headers: request_headers,
57
+ href: request.url,
58
+ body: parse_body(request.POST)
59
+ },
60
+ response: {
61
+ status: status,
62
+ body: parse_body(body),
63
+ type: type['Content-Type'],
64
+ }
65
+ })
66
+ rescue StandardError => error
67
+ # We should never fall in this part as the only errors that could result in this are errors
68
+ # in our logger (inside this same method)
69
+ @logger.error(error.message)
70
+ end
71
+
72
+ private
73
+ def get_request_headers_from_env(env)
74
+ env.select { |k,v| k.start_with? 'HTTP_'}.
75
+ transform_keys { |k| k.delete_prefix('HTTP_').split('_').join('-').upcase }
76
+ end
77
+
78
+ def build_message_from_request(request)
79
+ [
80
+ request.request_method.upcase,
81
+ [request.base_url,request.path].join(''),
82
+ ].join(' ')
83
+ end
84
+
85
+ def get_user_info_from_headers(headers)
86
+ PierLogging.request_logger_configuration.user_info_getter.call(headers)
87
+ end
88
+
89
+ def parse_body(body)
90
+ if body.is_a? String # when string
91
+ JSON.parse(body, nil, allow_blank: true)
92
+ elsif body.is_a? Array # Grape body
93
+ JSON.parse(body.last, nil, allow_blank: true)
94
+ elsif body.is_a? ActionDispatch::Response::RackBody # Rails body
95
+ JSON.parse(body.body, nil, allow_blank: true)
96
+ else
97
+ body
98
+ end
99
+ rescue
100
+ body
101
+ end
102
+
103
+ def redact_hash(hash)
104
+ hash.traverse do |k,v|
105
+ should_redact = REDACT_REPLACE_KEYS.any?{ |regex| k =~regex }
106
+ if (should_redact)
107
+ [k, REDACT_REPLACE_BY]
108
+ else
109
+ [k, v]
110
+ end
111
+ end
112
+ end
113
+
114
+ def determine_body_from_exception(exception)
115
+ { message: exception.message }
116
+ end
117
+
118
+ def determine_type_from_exception(exception)
119
+ 'application/json'
120
+ end
121
+
122
+ def determine_status_code_from_exception(exception)
123
+ exception_wrapper = ActionDispatch::ExceptionWrapper.new(nil, exception)
124
+ exception_wrapper.status_code
125
+ rescue
126
+ 500
127
+ end
128
+
129
+ def has_basic_credentials?(headers)
130
+ auth_header = headers['AUTHENTICATION'].to_s
131
+ return false if auth_header.blank?
132
+ # Optimization: https://github.com/JuanitoFatas/fast-ruby#stringcasecmp-vs-stringdowncase---code
133
+ return false if auth_header.split(' ', 2)[0].casecmp('basic') == 0
134
+ return false if auth_header.split(' ', 2)[1].blank?
135
+ return true
136
+ end
137
+
138
+ def get_basic_credentials_user(headers)
139
+ auth_headers = headers['AUTHENTICATION'].to_s
140
+ credentials = auth_headers.split(' ', 2)[1]
141
+ ::Base64.decode64(credentials).split(':', 2)[0]
142
+ end
143
+ end
144
+ end
@@ -0,0 +1,3 @@
1
+ module PierLogging
2
+ VERSION = "0.1.2"
3
+ end
@@ -0,0 +1,34 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "pier_logging/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "pier_logging"
8
+ spec.version = PierLogging::VERSION
9
+ spec.authors = ["Mauricio Banduk"]
10
+ spec.email = ["mauricio.banduk@pier.digital"]
11
+
12
+ spec.summary = %q{Structured log used on Pier Applications}
13
+ spec.description = %q{Defines a basic structure for general and request logging}
14
+ spec.homepage = "https://github.com/pier-digital"
15
+ spec.license = "MIT"
16
+
17
+ # Specify which files should be added to the gem when it is released.
18
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
19
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
20
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
21
+ end
22
+ spec.bindir = "exe"
23
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
24
+ spec.require_paths = ["lib"]
25
+
26
+ spec.add_dependency "ougai"
27
+ spec.add_dependency "awesome_print"
28
+ spec.add_dependency "rails"
29
+
30
+ spec.add_development_dependency "bundler", ">= 2.1.4"
31
+ spec.add_development_dependency "rake", ">= 12.3.3"
32
+ spec.add_development_dependency "minitest", ">= 5.8.4"
33
+ spec.add_development_dependency "byebug", ">= 11.1.3"
34
+ end
metadata ADDED
@@ -0,0 +1,164 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: pier_logging
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.2
5
+ platform: ruby
6
+ authors:
7
+ - Mauricio Banduk
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-07-03 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: ougai
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: awesome_print
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rails
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: bundler
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 2.1.4
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: 2.1.4
69
+ - !ruby/object:Gem::Dependency
70
+ name: rake
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: 12.3.3
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: 12.3.3
83
+ - !ruby/object:Gem::Dependency
84
+ name: minitest
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: 5.8.4
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: 5.8.4
97
+ - !ruby/object:Gem::Dependency
98
+ name: byebug
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: 11.1.3
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: 11.1.3
111
+ description: Defines a basic structure for general and request logging
112
+ email:
113
+ - mauricio.banduk@pier.digital
114
+ executables: []
115
+ extensions: []
116
+ extra_rdoc_files: []
117
+ files:
118
+ - ".github/workflows/publish.yml"
119
+ - ".gitignore"
120
+ - ".ruby-version"
121
+ - ".travis.yml"
122
+ - Gemfile
123
+ - Gemfile.lock
124
+ - LICENSE.txt
125
+ - README.md
126
+ - Rakefile
127
+ - bin/console
128
+ - bin/get_current_version.rb
129
+ - bin/notify_slack_github.sh
130
+ - bin/publish_gem.rb
131
+ - bin/rb_lint.sh
132
+ - bin/setup
133
+ - lib/pier_logging.rb
134
+ - lib/pier_logging/formatter/base.rb
135
+ - lib/pier_logging/formatter/json.rb
136
+ - lib/pier_logging/formatter/readable.rb
137
+ - lib/pier_logging/logger.rb
138
+ - lib/pier_logging/request_logger.rb
139
+ - lib/pier_logging/version.rb
140
+ - pier_logging.gemspec
141
+ homepage: https://github.com/pier-digital
142
+ licenses:
143
+ - MIT
144
+ metadata: {}
145
+ post_install_message:
146
+ rdoc_options: []
147
+ require_paths:
148
+ - lib
149
+ required_ruby_version: !ruby/object:Gem::Requirement
150
+ requirements:
151
+ - - ">="
152
+ - !ruby/object:Gem::Version
153
+ version: '0'
154
+ required_rubygems_version: !ruby/object:Gem::Requirement
155
+ requirements:
156
+ - - ">="
157
+ - !ruby/object:Gem::Version
158
+ version: '0'
159
+ requirements: []
160
+ rubygems_version: 3.1.2
161
+ signing_key:
162
+ specification_version: 4
163
+ summary: Structured log used on Pier Applications
164
+ test_files: []