bitlogger 2.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ data.tar.gz: eb9165304ef8b26161d44e1cb1bb938163ca7fd3
4
+ metadata.gz: dfedd4c3d0175367214984ac4b14d1f953595e1d
5
+ SHA512:
6
+ data.tar.gz: 327da1d6c28881b595dccb446b1ab55f5f928f5ee311ee5cc187ca63fcf78f536d8c50dd6e373d86a95df678f601455a39bc4172a5c9eea36f74fe0acf5d6e13
7
+ metadata.gz: 201ffca720dd5f9cf9a0bc6a4457ece3ab9f0005389439809c0d0f532e13b4a613eeeed52e65028388f4199070dc8476529db1762a1c5fb43b1db35586984e1c
@@ -0,0 +1,18 @@
1
+ .idea
2
+ *.gem
3
+ *.rbc
4
+ .bundle
5
+ .config
6
+ .yardoc
7
+ Gemfile.lock
8
+ InstalledFiles
9
+ _yardoc
10
+ coverage
11
+ doc/
12
+ lib/bundler/man
13
+ pkg
14
+ rdoc
15
+ spec/reports
16
+ test/tmp
17
+ test/version_tmp
18
+ tmp
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Evia Project - bitlogger
2
+ Copyright 2013 Relbit Ltd.
3
+
4
+ Unless explicitly noted otherwise, all files under this directory are
5
+ licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ not use this product except in compliance with the License attached
7
+ below.
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+
15
+ Apache License
16
+ Version 2.0, January 2004
17
+ http://www.apache.org/licenses/
18
+
19
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
20
+
21
+ 1. Definitions.
22
+
23
+ "License" shall mean the terms and conditions for use, reproduction,
24
+ and distribution as defined by Sections 1 through 9 of this document.
25
+
26
+ "Licensor" shall mean the copyright owner or entity authorized by
27
+ the copyright owner that is granting the License.
28
+
29
+ "Legal Entity" shall mean the union of the acting entity and all
30
+ other entities that control, are controlled by, or are under common
31
+ control with that entity. For the purposes of this definition,
32
+ "control" means (i) the power, direct or indirect, to cause the
33
+ direction or management of such entity, whether by contract or
34
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
35
+ outstanding shares, or (iii) beneficial ownership of such entity.
36
+
37
+ "You" (or "Your") shall mean an individual or Legal Entity
38
+ exercising permissions granted by this License.
39
+
40
+ "Source" form shall mean the preferred form for making modifications,
41
+ including but not limited to software source code, documentation
42
+ source, and configuration files.
43
+
44
+ "Object" form shall mean any form resulting from mechanical
45
+ transformation or translation of a Source form, including but
46
+ not limited to compiled object code, generated documentation,
47
+ and conversions to other media types.
48
+
49
+ "Work" shall mean the work of authorship, whether in Source or
50
+ Object form, made available under the License, as indicated by a
51
+ copyright notice that is included in or attached to the work
52
+ (an example is provided in the Appendix below).
53
+
54
+ "Derivative Works" shall mean any work, whether in Source or Object
55
+ form, that is based on (or derived from) the Work and for which the
56
+ editorial revisions, annotations, elaborations, or other modifications
57
+ represent, as a whole, an original work of authorship. For the purposes
58
+ of this License, Derivative Works shall not include works that remain
59
+ separable from, or merely link (or bind by name) to the interfaces of,
60
+ the Work and Derivative Works thereof.
61
+
62
+ "Contribution" shall mean any work of authorship, including
63
+ the original version of the Work and any modifications or additions
64
+ to that Work or Derivative Works thereof, that is intentionally
65
+ submitted to Licensor for inclusion in the Work by the copyright owner
66
+ or by an individual or Legal Entity authorized to submit on behalf of
67
+ the copyright owner. For the purposes of this definition, "submitted"
68
+ means any form of electronic, verbal, or written communication sent
69
+ to the Licensor or its representatives, including but not limited to
70
+ communication on electronic mailing lists, source code control systems,
71
+ and issue tracking systems that are managed by, or on behalf of, the
72
+ Licensor for the purpose of discussing and improving the Work, but
73
+ excluding communication that is conspicuously marked or otherwise
74
+ designated in writing by the copyright owner as "Not a Contribution."
75
+
76
+ "Contributor" shall mean Licensor and any individual or Legal Entity
77
+ on behalf of whom a Contribution has been received by Licensor and
78
+ subsequently incorporated within the Work.
79
+
80
+ 2. Grant of Copyright License. Subject to the terms and conditions of
81
+ this License, each Contributor hereby grants to You a perpetual,
82
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
83
+ copyright license to reproduce, prepare Derivative Works of,
84
+ publicly display, publicly perform, sublicense, and distribute the
85
+ Work and such Derivative Works in Source or Object form.
86
+
87
+ 3. Grant of Patent License. Subject to the terms and conditions of
88
+ this License, each Contributor hereby grants to You a perpetual,
89
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
90
+ (except as stated in this section) patent license to make, have made,
91
+ use, offer to sell, sell, import, and otherwise transfer the Work,
92
+ where such license applies only to those patent claims licensable
93
+ by such Contributor that are necessarily infringed by their
94
+ Contribution(s) alone or by combination of their Contribution(s)
95
+ with the Work to which such Contribution(s) was submitted. If You
96
+ institute patent litigation against any entity (including a
97
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
98
+ or a Contribution incorporated within the Work constitutes direct
99
+ or contributory patent infringement, then any patent licenses
100
+ granted to You under this License for that Work shall terminate
101
+ as of the date such litigation is filed.
102
+
103
+ 4. Redistribution. You may reproduce and distribute copies of the
104
+ Work or Derivative Works thereof in any medium, with or without
105
+ modifications, and in Source or Object form, provided that You
106
+ meet the following conditions:
107
+
108
+ (a) You must give any other recipients of the Work or
109
+ Derivative Works a copy of this License; and
110
+
111
+ (b) You must cause any modified files to carry prominent notices
112
+ stating that You changed the files; and
113
+
114
+ (c) You must retain, in the Source form of any Derivative Works
115
+ that You distribute, all copyright, patent, trademark, and
116
+ attribution notices from the Source form of the Work,
117
+ excluding those notices that do not pertain to any part of
118
+ the Derivative Works; and
119
+
120
+ (d) If the Work includes a "NOTICE" text file as part of its
121
+ distribution, then any Derivative Works that You distribute must
122
+ include a readable copy of the attribution notices contained
123
+ within such NOTICE file, excluding those notices that do not
124
+ pertain to any part of the Derivative Works, in at least one
125
+ of the following places: within a NOTICE text file distributed
126
+ as part of the Derivative Works; within the Source form or
127
+ documentation, if provided along with the Derivative Works; or,
128
+ within a display generated by the Derivative Works, if and
129
+ wherever such third-party notices normally appear. The contents
130
+ of the NOTICE file are for informational purposes only and
131
+ do not modify the License. You may add Your own attribution
132
+ notices within Derivative Works that You distribute, alongside
133
+ or as an addendum to the NOTICE text from the Work, provided
134
+ that such additional attribution notices cannot be construed
135
+ as modifying the License.
136
+
137
+ You may add Your own copyright statement to Your modifications and
138
+ may provide additional or different license terms and conditions
139
+ for use, reproduction, or distribution of Your modifications, or
140
+ for any such Derivative Works as a whole, provided Your use,
141
+ reproduction, and distribution of the Work otherwise complies with
142
+ the conditions stated in this License.
143
+
144
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
145
+ any Contribution intentionally submitted for inclusion in the Work
146
+ by You to the Licensor shall be under the terms and conditions of
147
+ this License, without any additional terms or conditions.
148
+ Notwithstanding the above, nothing herein shall supersede or modify
149
+ the terms of any separate license agreement you may have executed
150
+ with Licensor regarding such Contributions.
151
+
152
+ 6. Trademarks. This License does not grant permission to use the trade
153
+ names, trademarks, service marks, or product names of the Licensor,
154
+ except as required for reasonable and customary use in describing the
155
+ origin of the Work and reproducing the content of the NOTICE file.
156
+
157
+ 7. Disclaimer of Warranty. Unless required by applicable law or
158
+ agreed to in writing, Licensor provides the Work (and each
159
+ Contributor provides its Contributions) on an "AS IS" BASIS,
160
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
161
+ implied, including, without limitation, any warranties or conditions
162
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
163
+ PARTICULAR PURPOSE. You are solely responsible for determining the
164
+ appropriateness of using or redistributing the Work and assume any
165
+ risks associated with Your exercise of permissions under this License.
166
+
167
+ 8. Limitation of Liability. In no event and under no legal theory,
168
+ whether in tort (including negligence), contract, or otherwise,
169
+ unless required by applicable law (such as deliberate and grossly
170
+ negligent acts) or agreed to in writing, shall any Contributor be
171
+ liable to You for damages, including any direct, indirect, special,
172
+ incidental, or consequential damages of any character arising as a
173
+ result of this License or out of the use or inability to use the
174
+ Work (including but not limited to damages for loss of goodwill,
175
+ work stoppage, computer failure or malfunction, or any and all
176
+ other commercial damages or losses), even if such Contributor
177
+ has been advised of the possibility of such damages.
178
+
179
+ 9. Accepting Warranty or Additional Liability. While redistributing
180
+ the Work or Derivative Works thereof, You may choose to offer,
181
+ and charge a fee for, acceptance of support, warranty, indemnity,
182
+ or other liability obligations and/or rights consistent with this
183
+ License. However, in accepting such obligations, You may act only
184
+ on Your own behalf and on Your sole responsibility, not on behalf
185
+ of any other Contributor, and only if You agree to indemnify,
186
+ defend, and hold each Contributor harmless for any liability
187
+ incurred by, or claims asserted against, such Contributor by reason
188
+ of your accepting any such warranty or additional liability.
189
+
190
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,29 @@
1
+ # Bitlogger
2
+
3
+ Universal Relbit logger
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ gem 'bitlogger'
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install bitlogger
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Contributing
24
+
25
+ 1. Fork it
26
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
27
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
28
+ 4. Push to the branch (`git push origin my-new-feature`)
29
+ 5. Create new Pull Request
@@ -0,0 +1,18 @@
1
+ require "bundler/gem_tasks"
2
+
3
+ # Monkey patch Bundler gem_helper so we release to our gem server instead of rubygems.org
4
+ module Bundler
5
+ class GemHelper
6
+ def rubygem_push(path)
7
+ gem_server_url = 'http://gem.int.prg.relbit.com:80/'
8
+ sh("gem inabox '#{path}' --host #{gem_server_url}")
9
+ Bundler.ui.confirm "Pushed #{name} #{version} to #{gem_server_url}"
10
+ end
11
+ def perform_git_push(options = '')
12
+ puts "not pushing for now ... "
13
+ cmd = "git push #{options}"
14
+ out, code = sh_with_code(cmd)
15
+ raise "Couldn't git push. `#{cmd}' failed with the following output:\n\n#{out}\n" unless code == 0
16
+ end
17
+ end
18
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 2.0.0
@@ -0,0 +1,28 @@
1
+ # -*- encoding: utf-8 -*-
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'bitlogger/version'
5
+
6
+ Gem::Specification.new do |gem|
7
+ gem.name = 'bitlogger'
8
+ gem.version = Bitlogger::VERSION
9
+ gem.authors = ['kubo']
10
+ gem.email = ['jakub.jursa@relbit.com']
11
+ gem.description = 'Universal Relbit logger'
12
+ gem.summary = 'Universal Relbit logger'
13
+ gem.homepage = ''
14
+
15
+ gem.files = `git ls-files`.split($/)
16
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
17
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
18
+ gem.require_paths = ['lib']
19
+ gem.add_development_dependency 'geminabox', '~>0.10.1'
20
+ gem.add_development_dependency 'rspec', '~>2.14.1'
21
+ gem.add_development_dependency 'sinatra', '~>1.4.3'
22
+ gem.add_development_dependency 'thin', '~>1.5.1'
23
+ gem.add_dependency 'rest-client', '~>1.6.7'
24
+ gem.add_dependency 'json', '~>1.8.0'
25
+ gem.add_dependency 'rake', '~>10.1.0'
26
+ gem.add_dependency 'mime-types', '~>1.25'
27
+ gem.add_dependency 'rack', '~>1.4.5'
28
+ end
@@ -0,0 +1,28 @@
1
+ require 'date'
2
+ require 'json'
3
+ require 'rest_client'
4
+ require 'uri'
5
+
6
+ require 'bitlogger/buffer_decorator'
7
+ require 'bitlogger/dummy_formatter'
8
+ require 'bitlogger/filter_decorator'
9
+ require 'bitlogger/initializer'
10
+ require 'bitlogger/io_logger'
11
+ require 'bitlogger/json_formatter'
12
+ require 'bitlogger/loggable'
13
+ require 'bitlogger/logger_group'
14
+ require 'bitlogger/pretty_formatter'
15
+ require 'bitlogger/remote_logger'
16
+ require 'bitlogger/version'
17
+
18
+ require 'bitlogger/core_ext/uri'
19
+
20
+ module Bitlogger
21
+ LEVELS = [:debug, :info, :warn, :error, :fatal]
22
+
23
+ class << self
24
+ attr_accessor :logger
25
+ attr_accessor :level
26
+ def init(options); Initializer.new(options) end
27
+ end
28
+ end
@@ -0,0 +1,53 @@
1
+ module Bitlogger
2
+ class BufferDecorator
3
+ def initialize(target, method, max_size, max_time)
4
+ @target = target
5
+ @method = method.to_sym
6
+ @max_size = max_size
7
+ @max_time = max_time
8
+ @queue = Queue.new
9
+
10
+ create_alias
11
+ start_consuming
12
+ end
13
+
14
+ # @param [Array<Object>, Object] msgs
15
+ def push(msgs)
16
+ msgs = [msgs] unless msgs.is_a?(Array)
17
+ msgs.each { |msg| @queue << msg }
18
+ end
19
+
20
+ def empty
21
+ @last_emptying = Time.now
22
+ return if @queue.empty?
23
+
24
+ to_send = []
25
+ @queue.size.times { to_send << @queue.pop }
26
+ @target.send(@method, to_send)
27
+ end
28
+
29
+ private
30
+ def create_alias
31
+ method = @method
32
+ self.class.class_eval { alias_method method, :push }
33
+ end
34
+
35
+ def start_consuming
36
+ @last_emptying = Time.now
37
+ Thread.new do
38
+ loop do
39
+ wait while not time_to_empty?
40
+ empty
41
+ end
42
+ end
43
+ end
44
+
45
+ def wait
46
+ sleep(0.5)
47
+ end
48
+
49
+ def time_to_empty?
50
+ @queue.size >= @max_size or @last_emptying + @max_time <= Time.now
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,7 @@
1
+ module URI
2
+ def self.valid?(uri)
3
+ !!URI.parse(uri)
4
+ rescue URI::InvalidURIError
5
+ false
6
+ end
7
+ end
@@ -0,0 +1,10 @@
1
+ module Bitlogger
2
+ class DummyFormatter
3
+
4
+ # @param <Hash> msg
5
+ # @return <Hash>
6
+ def format_hash(hash)
7
+ hash
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,27 @@
1
+ module Bitlogger
2
+ class FilterDecorator
3
+ def initialize(target, method, level)
4
+ @target = target
5
+ @method = method.to_sym
6
+ @level = level
7
+
8
+ create_alias
9
+ end
10
+
11
+ def push(msgs)
12
+ msgs = [msgs] unless msgs.is_a?(Array)
13
+ to_send = msgs.select { |m| log_it?(m) }
14
+ @target.send(@method, to_send) unless to_send.empty?
15
+ end
16
+
17
+ private
18
+ def create_alias
19
+ method = @method
20
+ self.class.class_eval { alias_method method, :push }
21
+ end
22
+
23
+ def log_it?(msg)
24
+ !Bitlogger::LEVELS.index(msg[:level]).nil? && (Bitlogger::LEVELS.index(msg[:level])) >= Bitlogger::LEVELS.index(@level)
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,133 @@
1
+ module Bitlogger
2
+ class Initializer
3
+ def initialize(options)
4
+ @logger_group = LoggerGroup.new
5
+
6
+ if options.is_a?(Hash)
7
+ @logger_group << get_logger(self.class.default_options.merge(options))
8
+ elsif options.is_a?(Array)
9
+ options.each do |logger_options|
10
+ @logger_group << get_logger(self.class.default_options.merge(logger_options))
11
+ end
12
+ else
13
+ raise 'Options in wrong format'
14
+ end
15
+
16
+ Bitlogger.logger = @logger_group
17
+ end
18
+
19
+ def self.default_options
20
+ {
21
+ :target => STDERR,
22
+ :level => :warn,
23
+ :additional => {},
24
+ :buffered => false,
25
+ :buffer_size => 100,
26
+ :buffer_time => 5,
27
+ :ca_crt_path => nil # if set, then server's ssl crt will be verified
28
+ }
29
+ end
30
+
31
+ def get_logger(options)
32
+ target = options.fetch(:target)
33
+ level = options.fetch(:level).to_sym
34
+ additional = options.fetch(:additional)
35
+ buffered = options.fetch(:buffered)
36
+ buffer_size = options.fetch(:buffer_size)
37
+ buffer_time = options.fetch(:buffer_time)
38
+ ca_crt_path = options.fetch(:ca_crt_path)
39
+
40
+ type = nil
41
+
42
+ if target.is_a?(IO)
43
+ type = :io
44
+ elsif target.is_a?(String)
45
+ if target.start_with?('http') && URI.valid?(target)
46
+ type = :remote
47
+ else
48
+ type = :io
49
+ if target.upcase == 'STDOUT'
50
+ target = STDOUT
51
+ elsif target.upcase == 'STDERR'
52
+ target = STDERR
53
+ else
54
+ target = File.open(target, 'a')
55
+ end
56
+ end
57
+ else
58
+ raise StandardError, 'Unknown logging target type'
59
+ end
60
+
61
+ logger = nil
62
+ if type == :io
63
+ buffered = false
64
+ logger = get_filter_decorator(
65
+ get_io_logger(
66
+ get_pretty_formatter,
67
+ additional,
68
+ target
69
+ ),
70
+ :log,
71
+ level
72
+ )
73
+ at_exit { target.close }
74
+ elsif type == :remote
75
+ buffered = true
76
+ logger = get_filter_decorator(
77
+ get_remote_logger(
78
+ get_dummy_formatter,
79
+ additional,
80
+ target,
81
+ :logs,
82
+ ca_crt_path
83
+ ),
84
+ :log,
85
+ level
86
+ )
87
+ end
88
+
89
+ if buffered
90
+ logger = BufferDecorator.new(
91
+ logger,
92
+ :log,
93
+ buffer_size,
94
+ buffer_time
95
+ )
96
+ at_exit { Bitlogger.logger.empty }
97
+ end
98
+
99
+ logger
100
+ end
101
+
102
+ private
103
+ def get_pretty_formatter
104
+ Bitlogger::PrettyFormatter.new
105
+ end
106
+
107
+ def get_dummy_formatter
108
+ Bitlogger::DummyFormatter.new
109
+ end
110
+
111
+ def get_filter_decorator(target, method, level)
112
+ FilterDecorator.new(target, method, level)
113
+ end
114
+
115
+ def get_io_logger(formatter, additional, io)
116
+ Bitlogger::IoLogger.new(
117
+ formatter,
118
+ additional,
119
+ io
120
+ )
121
+ end
122
+
123
+ def get_remote_logger(formatter, additional, url, post_key, ca_crt_path)
124
+ Bitlogger::RemoteLogger.new(
125
+ formatter,
126
+ additional,
127
+ url,
128
+ post_key,
129
+ ca_crt_path
130
+ )
131
+ end
132
+ end
133
+ end
@@ -0,0 +1,25 @@
1
+ module Bitlogger
2
+ class IoLogger
3
+ def initialize(formatter, additional, io)
4
+ raise ArgumentError, "Io has to respond to :puts and :flush" unless io_valid?(io)
5
+ @formatter = formatter
6
+ @additional = additional
7
+ @io = io
8
+ end
9
+
10
+ # @param [Array<Hash>, Hash] msgs
11
+ def log(msgs)
12
+ msgs = [msgs] unless msgs.is_a?(Array)
13
+ msgs.each { |msg| @io.puts(@formatter.format_hash(@additional.merge(msg))) }
14
+ @io.flush
15
+ rescue => e
16
+ STDERR.puts("Error: #{e.class.name}, #{e.message}")
17
+ return false
18
+ end
19
+
20
+ private
21
+ def io_valid?(io)
22
+ io.respond_to?(:puts) and io.respond_to?(:flush)
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,10 @@
1
+ module Bitlogger
2
+ class JsonFormatter
3
+
4
+ # @param <Hash> msg
5
+ # @return <String>
6
+ def format_hash(hash)
7
+ hash.to_json
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,48 @@
1
+ module Bitlogger
2
+ module Loggable
3
+ attr_accessor :bitlogger_additional
4
+
5
+ def add_bitlogger_additional_info(additional)
6
+ @bitlogger_additional = additional
7
+ end
8
+
9
+ def llog(level, msg, exception = nil)
10
+ @bitlogger_additional ||= {}
11
+
12
+ exception_info = {}
13
+ if exception.is_a?(Exception)
14
+ exception_info[:exception_name] = exception.class.name
15
+ exception_info[:exception_message] = exception.message
16
+ exception_info[:exception_trace] = exception.backtrace.join("\n")
17
+ end
18
+
19
+ Bitlogger.logger.log(
20
+ {
21
+ :level => level,
22
+ :message => msg,
23
+ :timestamp => Time.now.to_i
24
+ }.merge(exception_info).merge(@bitlogger_additional)
25
+ )
26
+ end
27
+
28
+ def debug(msg)
29
+ self.llog(:debug, msg)
30
+ end
31
+
32
+ def info(msg)
33
+ self.llog(:info, msg)
34
+ end
35
+
36
+ def warn(msg, exception = nil)
37
+ self.llog(:warn, msg, exception)
38
+ end
39
+
40
+ def error(msg, exception = nil)
41
+ self.llog(:error, msg, exception)
42
+ end
43
+
44
+ def fatal(msg, exception = nil)
45
+ self.llog(:fatal, msg, exception)
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,19 @@
1
+ module Bitlogger
2
+ class LoggerGroup
3
+ def initialize
4
+ @loggers = []
5
+ end
6
+
7
+ def <<(logger)
8
+ @loggers << logger
9
+ end
10
+
11
+ def log(msg)
12
+ @loggers.each { |l| l.log(msg) }
13
+ end
14
+
15
+ def empty
16
+ @loggers.each { |l| l.empty if l.respond_to?(:empty) }
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,22 @@
1
+ module Bitlogger
2
+ class PrettyFormatter
3
+
4
+ def initialize
5
+ @offset = DateTime.now.offset
6
+ end
7
+
8
+ # @param <Hash> msg
9
+ # @return <String>
10
+ def format_hash(hash)
11
+ str = ""
12
+ hash.each do |k, v|
13
+ str += "[#{k}: #{v}] " unless k == :level or k == :timestamp
14
+ end
15
+
16
+ dt = DateTime.strptime(hash[:timestamp].to_s, '%s')
17
+ dt = dt.new_offset(@offset)
18
+
19
+ "[#{dt}] [#{hash[:level]}] #{str}"
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,47 @@
1
+ module Bitlogger
2
+ class RemoteLogger
3
+ def initialize(formatter, additional, url, post_key, ca_crt_path = nil)
4
+ raise ArgumentError, 'Invalid url' unless URI.valid?(url)
5
+ if !ca_crt_path.nil? && !File.exist?(ca_crt_path)
6
+ raise ArgumentError, "CA certificate not found (file `#{ca_crt_path}` missing)"
7
+ end
8
+ @formatter = formatter
9
+ @additional = additional
10
+ @url = url
11
+ @post_key = post_key
12
+ @ca_crt_path = ca_crt_path
13
+ end
14
+
15
+ # @param [Array<Hash>, Hash] msgs
16
+ def log(msgs)
17
+ msgs = [msgs] unless msgs.is_a?(Array)
18
+ msgs = msgs.map { |msg| @formatter.format_hash(@additional.merge(msg)) }
19
+ response = nil
20
+
21
+ if ssl_url?(@url)
22
+ opts = {
23
+ :method => :post,
24
+ :url => @url,
25
+ :payload => {@post_key => msgs.to_json}
26
+ }
27
+ if @ca_crt_path.nil?
28
+ opts[:verify_ssl] = 0
29
+ else
30
+ opts[:verify_ssl] = 1
31
+ opts[:ssl_ca_file] = @ca_crt_path
32
+ end
33
+ response = RestClient::Request.execute(opts)
34
+ else
35
+ response = RestClient.post(@url, {@post_key => msgs.to_json})
36
+ end
37
+ response.code == 200
38
+ rescue => e
39
+ STDERR.puts("Error: #{e.class.name}, #{e.message}")
40
+ return false
41
+ end
42
+
43
+ def ssl_url?(url)
44
+ url.start_with?('https://')
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,3 @@
1
+ module Bitlogger
2
+ VERSION = '2.0.1'
3
+ end
@@ -0,0 +1,123 @@
1
+ require 'spec_helper'
2
+ require 'sinatra/base'
3
+
4
+ describe Bitlogger, 'when logging to file' do
5
+ context 'when logging to unbuffered file' do
6
+ it 'logs to file' do
7
+ test_dir = '/tmp/bitlogger'
8
+ log_file = "#{test_dir}/bitlogger.log"
9
+ level = :debug
10
+ additional = { 'meh' => 'mnaf' }
11
+ FileUtils.rm_rf(test_dir)
12
+ FileUtils.mkdir_p(test_dir)
13
+ Bitlogger.init({
14
+ :target => log_file,
15
+ :level => level,
16
+ :additional => additional
17
+ })
18
+
19
+ msg = 'blahblah'
20
+ class A
21
+ include Bitlogger::Loggable
22
+ def a(m); debug(m) end
23
+ end
24
+
25
+ aa = A.new
26
+ aa.a(msg)
27
+ File.read(log_file).should end_with("[debug] [message: blahblah] [meh: mnaf] \n")
28
+ end
29
+ end
30
+
31
+ context 'when logging to multiple loggers to file' do
32
+ it 'works' do
33
+ test_dir = '/tmp/bitlogger'
34
+ log_file1 = "#{test_dir}/bitlogger1.log"
35
+ log_file2 = "#{test_dir}/bitlogger2.log"
36
+ FileUtils.rm_rf(test_dir)
37
+ FileUtils.mkdir_p(test_dir)
38
+
39
+ Bitlogger.init([
40
+ {
41
+ :target => log_file1,
42
+ :level => :debug
43
+ },
44
+ {
45
+ :target => log_file2,
46
+ :level => :warn
47
+ }
48
+ ])
49
+
50
+ msg = 'blahblah'
51
+ class A
52
+ include Bitlogger::Loggable
53
+ end
54
+
55
+ a = A.new
56
+ a.debug('this is debug message')
57
+ a.error('this is error message')
58
+
59
+ log1 = File.readlines(log_file1)
60
+ log1.any? { |l| l.include?('[message: this is debug message]')}.should be_true
61
+ log1.any? { |l| l.include?('[message: this is error message]')}.should be_true
62
+
63
+ log2 = File.readlines(log_file2)
64
+ log2.any? { |l| l.include?('[message: this is error message]')}.should be_true
65
+ end
66
+ end
67
+
68
+ context 'when logging to remote logger' do
69
+ it 'logs' do
70
+ $logs = []
71
+
72
+ class DummySupervisor < Sinatra::Base
73
+ use Rack::Auth::Basic, "Restricted Area" do |username, password|
74
+ [username, password] == ['admin', 'admin']
75
+ end
76
+
77
+ post '/logs' do
78
+ $logs += JSON.parse(params[:logs])
79
+ [200, 'ok']
80
+ end
81
+ end
82
+
83
+ server_up = false
84
+ Thread.new do
85
+ Rack::Handler::Thin.run(DummySupervisor, { :Port => 30000 }) do |server|
86
+ Thin::Logging.silent = true
87
+ server.ssl = true
88
+ server.ssl_options = {
89
+ :private_key_file => File.expand_path("#{File.dirname(__FILE__)}/ssl/key"),
90
+ :cert_chain_file => File.expand_path("#{File.dirname(__FILE__)}/ssl/crt"),
91
+ :verify_peer => false
92
+ }
93
+ server_up = true
94
+ end
95
+ end
96
+ sleep(0.1) while !server_up
97
+
98
+ level = :debug
99
+ additional = { 'meh' => 'mnaf' }
100
+ Bitlogger.init({
101
+ :target => 'https://admin:admin@localhost:30000/logs',
102
+ :level => level,
103
+ :additional => additional
104
+ })
105
+
106
+ msg = 'blahblah'
107
+ class A
108
+ include Bitlogger::Loggable
109
+ def a(m); debug(m) end
110
+ end
111
+
112
+ aa = A.new
113
+ aa.a(msg)
114
+
115
+ Bitlogger.logger.empty
116
+ $logs[0]['timestamp'].should be
117
+ $logs[0]['level'].should eql level.to_s
118
+ $logs[0]['message'].should eql msg
119
+ $logs[0].should include(additional)
120
+ #$logs[0][''].should eql be
121
+ end
122
+ end
123
+ end
@@ -0,0 +1,13 @@
1
+ -----BEGIN CERTIFICATE-----
2
+ MIICATCCAWoCCQCMf/4rAZ4unjANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB
3
+ VTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0
4
+ cyBQdHkgTHRkMB4XDTEyMTAwOTEzNTM1NVoXDTEzMTAwOTEzNTM1NVowRTELMAkG
5
+ A1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0
6
+ IFdpZGdpdHMgUHR5IEx0ZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAuCUw
7
+ pdmetkRdQS8//ac4qNMLMhWfVs5Lj/BpkYUu7hNl5LYvD2mww2aF267z3ZTeILXo
8
+ sS0cAPtsaqw+F3QKp0LTFYprQUParfcMUkB5u1osVLQMsd7q4vpdNJYoQqv04iCo
9
+ HHuh3Bqi54GXz2oGSG+7ax3YKtTBZlXIeZa4+1ECAwEAATANBgkqhkiG9w0BAQUF
10
+ AAOBgQC1WMCAFm86qt71M1+PBeHZOSeqjmZnytc2IPvNXNHM1ASvjd/BPAo16CEq
11
+ 7UlMiitXE1V1F1Pmi2+1INawbaz0GkVwaTuFjMI7QWfymhJ1X9u1ZfqgA5jdN28T
12
+ Mj+h7OIVRX9BH1hjemIY1nzqnRUoNB4yyMqSBfjBCUG4I92CXw==
13
+ -----END CERTIFICATE-----
@@ -0,0 +1,15 @@
1
+ -----BEGIN RSA PRIVATE KEY-----
2
+ MIICXQIBAAKBgQC4JTCl2Z62RF1BLz/9pzio0wsyFZ9WzkuP8GmRhS7uE2Xkti8P
3
+ abDDZoXbrvPdlN4gteixLRwA+2xqrD4XdAqnQtMVimtBQ9qt9wxSQHm7WixUtAyx
4
+ 3uri+l00lihCq/TiIKgce6HcGqLngZfPagZIb7trHdgq1MFmVch5lrj7UQIDAQAB
5
+ AoGAYKJjnSVOvKezqHl7Q0l12mKmBWqDa7JmxOqM++jAb/+OAS/6EkSMln4+0MJH
6
+ B4kP6GqN6iyZ/Ynzoycwjm4/CBNASIxLAsvSbF/OtnuhdHFhPqhxMKwniRjxBbDw
7
+ qf05iBXI/QuVK3hq6MUH6zuo9ereBI/9CmI9zc9LiESrSmECQQDkw3TFHNT7uyDs
8
+ N5Lp/s6zTOAIzipBodgQotgrB9oM5kKCOVeRsB9/7qhc2kAFtrMjlzzESeLSCO8m
9
+ 3cuqFWe3AkEAzhHNk6z+Po59IE4e1icyx3aXE1YpjBL+KoBPqRHMJJlF4k9s7SS3
10
+ rgKLXch0oLi8CQAoh2V5BkrGwxBggm/lNwJBAL1WUHU8UcMvtCYOMRhefvHDtMFU
11
+ 8YB01YGfZk7nJr/6bB2gHCxGmyulec+wC8Eu38GbUP4dMRApuNZwSDqzkK0CQD15
12
+ hCmc/w/sdBmSFJLwiK6Gi1VCbAyUkexd8OXQIGV+sCFubmFkhcNMkQT+SwSzd6z7
13
+ thuGQw+EeT0yAoiHFwsCQQCL5WjfMjIUHVHb32r64gisc+unbRt4ahHhUnEUwU+r
14
+ 9Y8EGZauq/9ZyT88vLy/5faKE0Okz6usRXTtjoupwGPi
15
+ -----END RSA PRIVATE KEY-----
@@ -0,0 +1,8 @@
1
+ require File.dirname(__FILE__) + '/../lib/bitlogger'
2
+ $LOAD_PATH.unshift(File.dirname(__FILE__))
3
+
4
+ RSpec.configure do |config|
5
+ config.color_enabled = true
6
+ config.tty = true
7
+ config.formatter = :documentation
8
+ end
metadata ADDED
@@ -0,0 +1,168 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: bitlogger
3
+ version: !ruby/object:Gem::Version
4
+ version: 2.0.1
5
+ platform: ruby
6
+ authors:
7
+ - kubo
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2014-03-26 00:00:00 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: geminabox
16
+ prerelease: false
17
+ requirement: &id001 !ruby/object:Gem::Requirement
18
+ requirements:
19
+ - - ~>
20
+ - !ruby/object:Gem::Version
21
+ version: 0.10.1
22
+ type: :development
23
+ version_requirements: *id001
24
+ - !ruby/object:Gem::Dependency
25
+ name: rspec
26
+ prerelease: false
27
+ requirement: &id002 !ruby/object:Gem::Requirement
28
+ requirements:
29
+ - - ~>
30
+ - !ruby/object:Gem::Version
31
+ version: 2.14.1
32
+ type: :development
33
+ version_requirements: *id002
34
+ - !ruby/object:Gem::Dependency
35
+ name: sinatra
36
+ prerelease: false
37
+ requirement: &id003 !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - ~>
40
+ - !ruby/object:Gem::Version
41
+ version: 1.4.3
42
+ type: :development
43
+ version_requirements: *id003
44
+ - !ruby/object:Gem::Dependency
45
+ name: thin
46
+ prerelease: false
47
+ requirement: &id004 !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ~>
50
+ - !ruby/object:Gem::Version
51
+ version: 1.5.1
52
+ type: :development
53
+ version_requirements: *id004
54
+ - !ruby/object:Gem::Dependency
55
+ name: rest-client
56
+ prerelease: false
57
+ requirement: &id005 !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ~>
60
+ - !ruby/object:Gem::Version
61
+ version: 1.6.7
62
+ type: :runtime
63
+ version_requirements: *id005
64
+ - !ruby/object:Gem::Dependency
65
+ name: json
66
+ prerelease: false
67
+ requirement: &id006 !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ~>
70
+ - !ruby/object:Gem::Version
71
+ version: 1.8.0
72
+ type: :runtime
73
+ version_requirements: *id006
74
+ - !ruby/object:Gem::Dependency
75
+ name: rake
76
+ prerelease: false
77
+ requirement: &id007 !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - ~>
80
+ - !ruby/object:Gem::Version
81
+ version: 10.1.0
82
+ type: :runtime
83
+ version_requirements: *id007
84
+ - !ruby/object:Gem::Dependency
85
+ name: mime-types
86
+ prerelease: false
87
+ requirement: &id008 !ruby/object:Gem::Requirement
88
+ requirements:
89
+ - - ~>
90
+ - !ruby/object:Gem::Version
91
+ version: "1.25"
92
+ type: :runtime
93
+ version_requirements: *id008
94
+ - !ruby/object:Gem::Dependency
95
+ name: rack
96
+ prerelease: false
97
+ requirement: &id009 !ruby/object:Gem::Requirement
98
+ requirements:
99
+ - - ~>
100
+ - !ruby/object:Gem::Version
101
+ version: 1.4.5
102
+ type: :runtime
103
+ version_requirements: *id009
104
+ description: Universal Relbit logger
105
+ email:
106
+ - jakub.jursa@relbit.com
107
+ executables: []
108
+
109
+ extensions: []
110
+
111
+ extra_rdoc_files: []
112
+
113
+ files:
114
+ - .gitignore
115
+ - Gemfile
116
+ - LICENSE
117
+ - README.md
118
+ - Rakefile
119
+ - VERSION
120
+ - bitlogger.gemspec
121
+ - lib/bitlogger.rb
122
+ - lib/bitlogger/buffer_decorator.rb
123
+ - lib/bitlogger/core_ext/uri.rb
124
+ - lib/bitlogger/dummy_formatter.rb
125
+ - lib/bitlogger/filter_decorator.rb
126
+ - lib/bitlogger/initializer.rb
127
+ - lib/bitlogger/io_logger.rb
128
+ - lib/bitlogger/json_formatter.rb
129
+ - lib/bitlogger/loggable.rb
130
+ - lib/bitlogger/logger_group.rb
131
+ - lib/bitlogger/pretty_formatter.rb
132
+ - lib/bitlogger/remote_logger.rb
133
+ - lib/bitlogger/version.rb
134
+ - spec/integration/complex_logging_spec.rb
135
+ - spec/integration/ssl/crt
136
+ - spec/integration/ssl/key
137
+ - spec/spec_helper.rb
138
+ homepage: ""
139
+ licenses: []
140
+
141
+ metadata: {}
142
+
143
+ post_install_message:
144
+ rdoc_options: []
145
+
146
+ require_paths:
147
+ - lib
148
+ required_ruby_version: !ruby/object:Gem::Requirement
149
+ requirements:
150
+ - &id010
151
+ - ">="
152
+ - !ruby/object:Gem::Version
153
+ version: "0"
154
+ required_rubygems_version: !ruby/object:Gem::Requirement
155
+ requirements:
156
+ - *id010
157
+ requirements: []
158
+
159
+ rubyforge_project:
160
+ rubygems_version: 2.0.6
161
+ signing_key:
162
+ specification_version: 4
163
+ summary: Universal Relbit logger
164
+ test_files:
165
+ - spec/integration/complex_logging_spec.rb
166
+ - spec/integration/ssl/crt
167
+ - spec/integration/ssl/key
168
+ - spec/spec_helper.rb