logrb 0.1.2

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: d2b3538c59ff3cd6964b1322b178ff41acd4a61f9cba41eb32f57433d9ccafa3
4
+ data.tar.gz: '0240916d10cc49d29214015d73d729eff14c72829212b86e57f17ea10be4395d'
5
+ SHA512:
6
+ metadata.gz: c552d0a05a75e68885c9a401d17350cabc4a7257e8bf0016083567fa59992a243764ae017daddeaa9b5312f59e40726fb5742223ea67b058bb935454458a486e
7
+ data.tar.gz: 6c28c536a1afdd1eda0395ed6683127633e8d6701a39fb73294bc4a342aff5dc857f08c332aac0339a2e68d386e86d07d57ec76b04a083d2e18fa8f15c1c57b2
@@ -0,0 +1,16 @@
1
+ name: Ruby
2
+
3
+ on: [push,pull_request]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v2
10
+ - name: Set up Ruby
11
+ uses: ruby/setup-ruby@v1
12
+ with:
13
+ ruby-version: 3.0.2
14
+ bundler-cache: true
15
+ - name: Run the default task
16
+ run: bundle exec rake
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,32 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.7
3
+ NewCops: enable
4
+
5
+ Style/StringLiterals:
6
+ Enabled: true
7
+ EnforcedStyle: double_quotes
8
+
9
+ Style/StringLiteralsInInterpolation:
10
+ Enabled: true
11
+ EnforcedStyle: double_quotes
12
+
13
+ Layout/LineLength:
14
+ Max: 120
15
+
16
+ Metrics/ClassLength:
17
+ Enabled: false
18
+
19
+ Metrics/MethodLength:
20
+ Enabled: false
21
+
22
+ Metrics/BlockLength:
23
+ Enabled: false
24
+
25
+ Metrics/AbcSize:
26
+ Enabled: false
27
+
28
+ Metrics/CyclomaticComplexity:
29
+ Enabled: false
30
+
31
+ Metrics/PerceivedComplexity:
32
+ Enabled: false
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at hey@vito.io. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in logrb.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 1.7"
data/Gemfile.lock ADDED
@@ -0,0 +1,58 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ logrb (0.1.2)
5
+ hexdump (~> 0.3.0)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ ast (2.4.2)
11
+ diff-lcs (1.4.4)
12
+ hexdump (0.3.0)
13
+ parallel (1.20.1)
14
+ parser (3.0.2.0)
15
+ ast (~> 2.4.1)
16
+ rainbow (3.0.0)
17
+ rake (13.0.6)
18
+ regexp_parser (2.1.1)
19
+ rexml (3.2.5)
20
+ rspec (3.10.0)
21
+ rspec-core (~> 3.10.0)
22
+ rspec-expectations (~> 3.10.0)
23
+ rspec-mocks (~> 3.10.0)
24
+ rspec-core (3.10.1)
25
+ rspec-support (~> 3.10.0)
26
+ rspec-expectations (3.10.1)
27
+ diff-lcs (>= 1.2.0, < 2.0)
28
+ rspec-support (~> 3.10.0)
29
+ rspec-mocks (3.10.2)
30
+ diff-lcs (>= 1.2.0, < 2.0)
31
+ rspec-support (~> 3.10.0)
32
+ rspec-support (3.10.2)
33
+ rubocop (1.19.0)
34
+ parallel (~> 1.10)
35
+ parser (>= 3.0.0.0)
36
+ rainbow (>= 2.2.2, < 4.0)
37
+ regexp_parser (>= 1.8, < 3.0)
38
+ rexml
39
+ rubocop-ast (>= 1.9.1, < 2.0)
40
+ ruby-progressbar (~> 1.7)
41
+ unicode-display_width (>= 1.4.0, < 3.0)
42
+ rubocop-ast (1.10.0)
43
+ parser (>= 3.0.1.1)
44
+ ruby-progressbar (1.11.0)
45
+ unicode-display_width (2.0.0)
46
+
47
+ PLATFORMS
48
+ x86_64-darwin-20
49
+ x86_64-linux
50
+
51
+ DEPENDENCIES
52
+ logrb!
53
+ rake (~> 13.0)
54
+ rspec (~> 3.0)
55
+ rubocop (~> 1.7)
56
+
57
+ BUNDLED WITH
58
+ 2.2.22
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Victor Gama
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,135 @@
1
+ # Logrb
2
+
3
+ **Logrb** is a small logging library for Ruby, inspired by Go's Zap.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'logrb'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install logrb
20
+
21
+ ## Usage
22
+
23
+ Start by creating a new logger:
24
+
25
+ ```ruby
26
+ require 'logrb'
27
+
28
+ logger = Logrb.new($stdout)
29
+
30
+ # Additionally, other options can be passed to the initializer:
31
+ # logger = Logrb.new($stdout, [format: :json], [level: :warn], [sample_field: :foo])
32
+ ```
33
+
34
+ Then, call either `error`, `fatal`, `warn`, `info`, `debug`, or `dump`.
35
+
36
+ ```ruby
37
+ logger.debug("Email dispatched", address: "foo@bar.com")
38
+ # => 2021-08-16T08:42:26.528-0300 DEBUG: <main>: Email dispatched {:address=>"foo@bar.com"}
39
+
40
+ logger.info("Operation completed", duration: 3.4)
41
+ # => 2021-08-16T08:43:00.790-0300 INFO: <main>: Operation completed {:duration=>3.4}
42
+
43
+ logger.warn("Attention is required", event: :something)
44
+ # => 2021-08-16T08:44:16.172-0300 WARN: <main>: Attention is required {:event=>:something}
45
+
46
+ logger.error("Something went wrong", StandardError.new("Boom"), user_id: 27)
47
+ # => 2021-08-16T08:47:09.968-0300 ERROR: <main>: Something went wrong {:user_id=>27}: Boom
48
+ # (irb):2 in `<main>'
49
+ # /usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb/workspace.rb:116 in `eval'
50
+ # /usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb/workspace.rb:116 in `evaluate'
51
+ # /usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb/context.rb:450 in `evaluate'
52
+ # /usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb.rb:567 in `block (2 levels) in eval_input'
53
+ # /usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb.rb:751 in `signal_status'
54
+ # /usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb.rb:548 in `block in eval_input'
55
+ # /usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb/ruby-lex.rb:251 in `block (2 levels) in each_top_level_statement'
56
+ # /usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb/ruby-lex.rb:233 in `loop'
57
+ # /usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb/ruby-lex.rb:233 in `block in each_top_level_statement'
58
+ # /usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb/ruby-lex.rb:232 in `catch'
59
+ # /usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb/ruby-lex.rb:232 in `each_top_level_statement'
60
+ # /usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb.rb:547 in `eval_input'
61
+ # /usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb.rb:481 in `block in run'
62
+ # /usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb.rb:480 in `catch'
63
+ # /usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb.rb:480 in `run'
64
+ # /usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb.rb:409 in `start'
65
+
66
+ logger.dump("Received data", "\xC0\xFF\xEE\xBA\xBE")
67
+ # => 2021-08-16T08:49:52.371-0300 DUMP: <main>: Received data
68
+ # 00000000 c0 ff ee ba be |.....|
69
+ # 00000005
70
+ #
71
+ ```
72
+
73
+ For production environments, it is recommended to use a JSON format, which spans
74
+ one line per entry:
75
+
76
+ ```ruby
77
+ logger.debug("Email dispatched", address: "foo@bar.com")
78
+ # => {"level":"debug","caller":"(irb):10","msg":"Email dispatched","ts":1629115513,"address":"foo@bar.com"}
79
+
80
+ logger.info("Operation completed", duration: 3.4)
81
+ # => {"level":"info","caller":"(irb):11","msg":"Operation completed","ts":1629115513,"duration":3.4}
82
+
83
+ logger.warn("Attention is required", event: :something)
84
+ # => {"level":"warn","caller":"(irb):12","msg":"Attention is required","ts":1629115513,"event":"something"}
85
+
86
+ logger.error("Something went wrong", StandardError.new("Boom"), user_id: 27)
87
+ # => {"level":"error","caller":"(irb):13","msg":"Something went wrong","ts":1629115514,"stacktrace":"(irb):13 in `<main>'\n/usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb/workspace.rb:116 in `eval'\n/usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb/workspace.rb:116 in `evaluate'\n/usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb/context.rb:450 in `evaluate'\n/usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb.rb:567 in `block (2 levels) in eval_input'\n/usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb.rb:751 in `signal_status'\n/usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb.rb:548 in `block in eval_input'\n/usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb/ruby-lex.rb:251 in `block (2 levels) in each_top_level_statement'\n/usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb/ruby-lex.rb:233 in `loop'\n/usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb/ruby-lex.rb:233 in `block in each_top_level_statement'\n/usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb/ruby-lex.rb:232 in `catch'\n/usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb/ruby-lex.rb:232 in `each_top_level_statement'\n/usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb.rb:547 in `eval_input'\n/usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb.rb:481 in `block in run'\n/usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb.rb:480 in `catch'\n/usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb.rb:480 in `run'\n/usr/local/Cellar/ruby/3.0.2/lib/ruby/3.0.0/irb.rb:409 in `start'","user_id":27}
88
+
89
+ logger.dump("Received data", "\xC0\xFF\xEE\xBA\xBE")
90
+ # => {"level":"dump","caller":"(irb):14","msg":"Received data","ts":1629115514,"dump":"00000000 c0 ff ee ba be |.....|\n00000005"}
91
+
92
+ ```
93
+
94
+ ## Development
95
+
96
+ 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.
97
+
98
+ 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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
99
+
100
+ ## Contributing
101
+
102
+ Bug reports and pull requests are welcome on GitHub at https://github.com/heyvito/logrb. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/heyvito/logrb/blob/master/CODE_OF_CONDUCT.md).
103
+
104
+ ## Code of Conduct
105
+
106
+ Everyone interacting in the Logrb project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/heyvito/logrb/blob/master/CODE_OF_CONDUCT.md).
107
+
108
+ ## License
109
+
110
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
111
+
112
+ ```
113
+ The MIT License (MIT)
114
+
115
+ Copyright (c) 2021 Victor Gama
116
+
117
+ Permission is hereby granted, free of charge, to any person obtaining a copy
118
+ of this software and associated documentation files (the "Software"), to deal
119
+ in the Software without restriction, including without limitation the rights
120
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
121
+ copies of the Software, and to permit persons to whom the Software is
122
+ furnished to do so, subject to the following conditions:
123
+
124
+ The above copyright notice and this permission notice shall be included in
125
+ all copies or substantial portions of the Software.
126
+
127
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
128
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
129
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
130
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
131
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
132
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
133
+ THE SOFTWARE.
134
+
135
+ ```
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "logrb"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ 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,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Logrb
4
+ VERSION = "0.1.2"
5
+ end
data/lib/logrb.rb ADDED
@@ -0,0 +1,274 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "logrb/version"
4
+ require "hexdump"
5
+ require "json"
6
+
7
+ # Logrb provides a facility for working with logs in text and json formats.
8
+ # All instances share a single mutex to ensure logging consistency.
9
+ # The following attributes are available:
10
+ #
11
+ # fields - A hash containing metadata to be included in logs emitted by this
12
+ # instance.
13
+ # level - The level filter for the instance. Valid values are :error, :fatal,
14
+ # :info, :warn, and :debug
15
+ # format - The format to output logs. Supports :text and :json.
16
+ #
17
+ # Each instance exposes the following methods, which accepts an arbitrary
18
+ # number of key-value pairs to be included in the logged message:
19
+ #
20
+ # #error(msg, error=nil, **fields): Outputs an error entry. When `error` is
21
+ # present, attempts to obtain backtrace information and also includes it
22
+ # to the emitted entry.
23
+ #
24
+ # #fatal(msg, **fields): Outputs a fatal entry. Calling fatal causes the
25
+ # current process to exit with a status 1.
26
+ #
27
+ # #warn(msg, **fields): Outputs a warning entry.
28
+ # #info(msg, **fields): Outputs a informational entry.
29
+ # #debug(msg, **fields): Outputs a debug entry.
30
+ # #dump(msg, data=nil): Outputs a given String or Array of bytes using the
31
+ # same format as `hexdump -C`.
32
+ class Logrb
33
+ attr_accessor :fields, :level, :format
34
+
35
+ COLORS = {
36
+ error: 31,
37
+ fatal: 31,
38
+ unknown: 0,
39
+ info: 36,
40
+ warn: 33,
41
+ debug: 30,
42
+ reset: 0,
43
+ dump: 37
44
+ }.freeze
45
+
46
+ BACKGROUNDS = {
47
+ debug: 107
48
+ }.freeze
49
+
50
+ LEVELS = {
51
+ error: 4,
52
+ fatal: 4,
53
+ unknown: 4,
54
+ warn: 3,
55
+ info: 2,
56
+ debug: 1,
57
+ reset: 1
58
+ }.freeze
59
+
60
+ # Internal: A mutex instance used for synchronizing the usage of the output
61
+ # IO.
62
+ def self.mutex
63
+ @mutex ||= Mutex.new
64
+ end
65
+
66
+ # Initializes a new Logger instance that outputs logs to a provided output.
67
+ #
68
+ # output - an IO-like object that implements a #write method.
69
+ # format - Optional. Indicates the format used to output log entries.
70
+ # Supports :text (default) and :json.
71
+ # level - Level to filter this logger instance
72
+ # fields - Fields to include in emitted entries
73
+ def initialize(output, format: :text, level: :debug, **fields)
74
+ @output = output
75
+ @format = format
76
+ @fields = fields
77
+ @level = level
78
+ end
79
+
80
+ # Returns a new logger instance using the same output of its parent's, with
81
+ # an optional set of fields to be merged against the parent's fields.
82
+ #
83
+ # fields - A Hash containing metadata to be included in all output entries
84
+ # emitted from the returned instance.
85
+ def with_fields(**fields)
86
+ inst = Logrb.new(@output, format: @format, level: @level)
87
+ inst.fields = @fields.merge(fields)
88
+ inst
89
+ end
90
+
91
+ LEVELS.except(:error).each_key do |name|
92
+ define_method(name) do |msg, **fields|
93
+ return if LEVELS[@level] > LEVELS[name]
94
+
95
+ wrap(name, msg, nil, fields)
96
+ nil
97
+ end
98
+ end
99
+
100
+ # Public: Emits an error to the log output. When error is provided, this
101
+ # method attempts to gather a stacktrace to include in the emitted entry.
102
+ def error(msg, error = nil, **fields)
103
+ return if LEVELS[@level] > LEVELS[:error]
104
+
105
+ wrap(:error, msg, error, fields)
106
+ nil
107
+ end
108
+
109
+ # Public: Dumps a given String or Array in the same format as `hexdump -C`.
110
+ def dump(log, data = nil, **fields)
111
+ return if LEVELS[@level] > LEVELS[:debug]
112
+
113
+ if data.nil?
114
+ data = log
115
+ log = nil
116
+ end
117
+
118
+ data = data.pack("C*") if data.is_a? Array
119
+ dump = []
120
+ padding = @format == :json ? "" : " "
121
+ Hexdump.dump(data, output: dump)
122
+ dump.map! { |line| "#{padding}#{line.chomp}" }
123
+ dump = dump.join("\n")
124
+
125
+ if @format == :json
126
+ fields[:dump] = dump
127
+ dump = nil
128
+ end
129
+ wrap(:dump, log || "", nil, fields)
130
+ write_output("#{dump}\n\n") unless dump.nil?
131
+ end
132
+
133
+ private
134
+
135
+ # Internal: Formats a given text using the ANSI escape sequences. Notice
136
+ # that this method does not attempt to determine whether the current output
137
+ # supports escape sequences.
138
+ def color(color, text)
139
+ bg = BACKGROUNDS[color]
140
+ reset_bg = ""
141
+ if bg
142
+ bg = "\e[#{bg}m"
143
+ reset_bg = "\e[49m"
144
+ end
145
+ "#{bg}\e[#{COLORS[color]}m#{text}\e[#{COLORS[:reset]}m#{reset_bg}"
146
+ end
147
+
148
+ # Internal: Removes all backtrace frames pointing to the logging facility
149
+ # itself.
150
+ def clean_caller_locations
151
+ caller_locations.reject { |t| t.absolute_path&.end_with?("logrb.rb") }
152
+ end
153
+
154
+ # Internal: Returns the caller of a function, returning a pair containing
155
+ # its path and base method name.
156
+ def determine_caller
157
+ c = clean_caller_locations.first
158
+ [normalize_location(c), c.base_label]
159
+ end
160
+
161
+ # Internal: Performs a cleanup for a given backtrace frame.
162
+ #
163
+ # trace - Trace to be clean.
164
+ # include_function_name - Optional. When true, includes the function name
165
+ # on the normalized string. Defaults to false.
166
+ def normalize_location(trace, include_function_name: false)
167
+ path = trace.absolute_path
168
+ return trace.to_s if path.nil?
169
+
170
+ if (root = Gem.path.find { |p| path.start_with?(p) })
171
+ path = "$GEM_PATH#{path[root.length..]}"
172
+ end
173
+ "#{path}:#{trace.lineno}#{include_function_name ? " in `#{trace.label}'" : ""}"
174
+ end
175
+
176
+ # Internal: Returns a string containing a stacktrace of the current
177
+ # invocation.
178
+ def stack_trace(trace = clean_caller_locations)
179
+ trace.map { |s| normalize_location(s, include_function_name: true) }.join("\n")
180
+ end
181
+
182
+ # Internal: Composes a log line with given information.
183
+ # level - The severity of the log message
184
+ # caller_meta - An Array containing the caller's location and name
185
+ # msg - The message to be logged
186
+ # fields - A Hash of fields to be included in the entry
187
+ def compose_line(level, caller_meta, msg, fields)
188
+ ts = Time.now.strftime("%Y-%m-%dT%H:%M:%S.%L%z")
189
+ msg = " #{msg}" unless msg.empty?
190
+ fields_str = if fields.empty?
191
+ ""
192
+ else
193
+ " #{fields}"
194
+ end
195
+ level_str = color(level, level.to_s.upcase)
196
+ "#{ts} #{level_str}: #{caller_meta.last}:#{msg}#{fields_str}"
197
+ end
198
+
199
+ # Internal: Logs a text entry to the current output.
200
+ # level - The severity of the message to be logged.
201
+ # msg - The message to be logged
202
+ # error - Either an Exception object or nil. This parameter is used
203
+ # to provide extra information on the logged entry.
204
+ # fields - A Hash containing metadata to be included in the logged
205
+ # entry.
206
+ # caller_meta - An Array containing the caller's location and name.
207
+ def text(level, msg, error, fields, caller_meta)
208
+ fields ||= {}
209
+ fields.merge! @fields
210
+ write_output(compose_line(level, caller_meta, msg, fields))
211
+ if (error_message = error&.message)
212
+ write_output(": #{error_message}")
213
+ end
214
+ write_output("\n")
215
+ return unless level == :error
216
+
217
+ backtrace_str = backtrace(error)
218
+ .split("\n")
219
+ .map { |s| " #{s}" }.join("\n")
220
+ write_output(backtrace_str)
221
+ write_output("\n")
222
+ end
223
+
224
+ # Internal: Attempts to obtain a backtrace from a provided object. In case
225
+ # the object does not include backtrace metadata, uses #stack_trace as a
226
+ # fallback.
227
+ def backtrace(from)
228
+ if from.respond_to?(:backtrace_locations) && !from.backtrace_locations.nil?
229
+ stack_trace(from.backtrace_locations)
230
+ else
231
+ stack_trace
232
+ end
233
+ end
234
+
235
+ # Internal: Writes a given value to the current's output IO. Calls to this
236
+ # method are thread-safe.
237
+ def write_output(text)
238
+ Logrb.mutex.synchronize do
239
+ @output.write(text)
240
+ end
241
+ end
242
+
243
+ # Internal: Logs a JSON entry to the current output.
244
+ # level - The severity of the message to be logged.
245
+ # msg - The message to be logged
246
+ # error - Either an Exception object or nil. This parameter is used
247
+ # to provide extra information on the logged entry.
248
+ # fields - A Hash containing metadata to be included in the logged
249
+ # entry.
250
+ # caller_meta - An Array containing the caller's location and name.
251
+ def json(level, msg, error, fields, caller_meta)
252
+ fields ||= {}
253
+ fields.merge! @fields
254
+ data = {
255
+ level: level,
256
+ caller: caller_meta.first,
257
+ msg: msg,
258
+ ts: Time.now.utc.to_i
259
+ }
260
+
261
+ data[:stacktrace] = backtrace(error) if level == :error
262
+
263
+ data.merge!(fields)
264
+ write_output("#{data.to_json}\n")
265
+ end
266
+
267
+ # Internal: Dynamically invokes the current log formatter for the
268
+ # provided arguments. For further information, see #text and #json
269
+ def wrap(level, msg, error, fields)
270
+ msg = msg.to_s
271
+ send(@format, level, msg, error, fields, determine_caller)
272
+ exit 1 if level == :fatal
273
+ end
274
+ end
data/logrb.gemspec ADDED
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/logrb/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "logrb"
7
+ spec.version = Logrb::VERSION
8
+ spec.authors = ["Victor Gama"]
9
+ spec.email = ["hey@vito.io"]
10
+
11
+ spec.summary = "Small logger inspired by Go's Zap"
12
+ spec.description = "Small logger inspired by Go's Zap"
13
+ spec.homepage = "https://github.com/heyvito/logrb"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 2.7.0"
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = spec.homepage
19
+ spec.metadata["changelog_uri"] = spec.homepage
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added
23
+ # into git.
24
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
25
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
26
+ end
27
+ spec.bindir = "exe"
28
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
29
+ spec.require_paths = ["lib"]
30
+
31
+ spec.add_dependency "hexdump", "~> 0.3.0"
32
+ end
metadata ADDED
@@ -0,0 +1,75 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: logrb
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.2
5
+ platform: ruby
6
+ authors:
7
+ - Victor Gama
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-08-16 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: hexdump
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.3.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.3.0
27
+ description: Small logger inspired by Go's Zap
28
+ email:
29
+ - hey@vito.io
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".github/workflows/main.yml"
35
+ - ".gitignore"
36
+ - ".rspec"
37
+ - ".rubocop.yml"
38
+ - CODE_OF_CONDUCT.md
39
+ - Gemfile
40
+ - Gemfile.lock
41
+ - LICENSE.txt
42
+ - README.md
43
+ - Rakefile
44
+ - bin/console
45
+ - bin/setup
46
+ - lib/logrb.rb
47
+ - lib/logrb/version.rb
48
+ - logrb.gemspec
49
+ homepage: https://github.com/heyvito/logrb
50
+ licenses:
51
+ - MIT
52
+ metadata:
53
+ homepage_uri: https://github.com/heyvito/logrb
54
+ source_code_uri: https://github.com/heyvito/logrb
55
+ changelog_uri: https://github.com/heyvito/logrb
56
+ post_install_message:
57
+ rdoc_options: []
58
+ require_paths:
59
+ - lib
60
+ required_ruby_version: !ruby/object:Gem::Requirement
61
+ requirements:
62
+ - - ">="
63
+ - !ruby/object:Gem::Version
64
+ version: 2.7.0
65
+ required_rubygems_version: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - ">="
68
+ - !ruby/object:Gem::Version
69
+ version: '0'
70
+ requirements: []
71
+ rubygems_version: 3.2.22
72
+ signing_key:
73
+ specification_version: 4
74
+ summary: Small logger inspired by Go's Zap
75
+ test_files: []