net_tcp_client 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/LICENSE.txt +201 -0
- data/README.md +101 -0
- data/Rakefile +28 -0
- data/lib/net/tcp_client.rb +5 -0
- data/lib/net/tcp_client/exceptions.rb +35 -0
- data/lib/net/tcp_client/logging.rb +191 -0
- data/lib/net/tcp_client/tcp_client.rb +604 -0
- data/lib/net/tcp_client/version.rb +5 -0
- data/test/simple_tcp_server.rb +114 -0
- data/test/tcp_client_test.rb +190 -0
- metadata +58 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA1:
|
3
|
+
metadata.gz: cf88786139faafadc4b1f1fad33c681c4137b083
|
4
|
+
data.tar.gz: ef3ed6ce5f9ab0620bc7ef8746d3d0291ae03364
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 610d155da8d923ab15282c013900f16a9a624855a154ce97ea74388820352ebb112dc7fe19aa777aaef7d6b388a0da3c611f2b24a8dec8cb37b58b669e90f314
|
7
|
+
data.tar.gz: 30c4854a12224824e2e804f185ca8ca96c9dab9f809a4b669813a396b47ba4b1f3f266b367ec4527fa3cf13aa6383435d6f09dc91c0c66af0e5fa9ca8a2459d7
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright 2012, 2013, 2014 Reid Morrison
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|
data/README.md
ADDED
@@ -0,0 +1,101 @@
|
|
1
|
+
net_tcp_client
|
2
|
+
==============
|
3
|
+
|
4
|
+
Net::TCPClient is a TCP Socket Client with built-in timeouts, retries, and logging
|
5
|
+
|
6
|
+
* http://github.com/reidmorrison/net_tcp_client
|
7
|
+
|
8
|
+
## Introduction
|
9
|
+
|
10
|
+
Net::TCPClient implements resilience features that most developers wish was
|
11
|
+
already included in the standard Ruby libraries.
|
12
|
+
|
13
|
+
With so many "client" libraries to servers such us memcache, MongoDB, Redis, etc.
|
14
|
+
their focus is on the communication formats and messaging interactions. As a result
|
15
|
+
adding resilience is usually an after thought.
|
16
|
+
|
17
|
+
More importantly the way that each client implements connection failure handling
|
18
|
+
varies dramatically. The purpose of this library is to extract the best
|
19
|
+
of all the socket error handling out there and create a consistent way of dealing
|
20
|
+
with connection failures.
|
21
|
+
|
22
|
+
Another important feature is that the _connect_ and _read_ API's use timeout's to
|
23
|
+
prevent a network issue from "hanging" the client program.
|
24
|
+
|
25
|
+
## Net::TCPClient API
|
26
|
+
|
27
|
+
Net::TCPClient is a drop in replacement for TCPSocket when used as a client.
|
28
|
+
|
29
|
+
The initializer is the only deviation since it accepts several new options
|
30
|
+
that support automatic failover, re-connect and messaging retries.
|
31
|
+
|
32
|
+
## Example
|
33
|
+
|
34
|
+
Connect to a server at address `localhost`, and on port `3300`.
|
35
|
+
|
36
|
+
Specify a custom retry interval and retry counts during connection.
|
37
|
+
|
38
|
+
```ruby
|
39
|
+
require 'net/tcp_client'
|
40
|
+
|
41
|
+
Net::TCPClient.connect(
|
42
|
+
server: 'localhost:3300',
|
43
|
+
connect_retry_interval: 0.1,
|
44
|
+
connect_retry_count: 5
|
45
|
+
) do |client|
|
46
|
+
# If the connection is lost, create a new one and retry the send
|
47
|
+
client.retry_on_connection_failure do
|
48
|
+
client.send('Update the database')
|
49
|
+
end
|
50
|
+
response = client.read(20)
|
51
|
+
puts "Received: #{response}"
|
52
|
+
end
|
53
|
+
```
|
54
|
+
|
55
|
+
## Dependencies
|
56
|
+
|
57
|
+
- Ruby 1.9.3, JRuby 1.7, or greater
|
58
|
+
|
59
|
+
There is a soft dependency on SemanticLogger. It will use SemanticLogger only if
|
60
|
+
it is already available, otherwise any other standard Ruby logger can be used.
|
61
|
+
- [SemanticLogger](http://github.com/reidmorrison/semantic_logger)
|
62
|
+
|
63
|
+
## Production Use
|
64
|
+
|
65
|
+
Net::TCPClient was built for and is being used in a high performance, highly concurrent
|
66
|
+
production environment. The resilient capabilities of Net::TCPClient are put to the
|
67
|
+
test on a daily basis, especially with connections over the internet between
|
68
|
+
remote data centers.
|
69
|
+
|
70
|
+
## Installation
|
71
|
+
|
72
|
+
gem install net_tcp_client
|
73
|
+
|
74
|
+
## Meta
|
75
|
+
|
76
|
+
* Code: `git clone git://github.com/reidmorrison/net_tcp_client.git`
|
77
|
+
* Home: <https://github.com/reidmorrison/net_tcp_client>
|
78
|
+
* Bugs: <http://github.com/reidmorrison/net_tcp_client/issues>
|
79
|
+
* Gems: <http://rubygems.org/gems/net_tcp_client>
|
80
|
+
|
81
|
+
This project uses [Semantic Versioning](http://semver.org/).
|
82
|
+
|
83
|
+
## Author
|
84
|
+
|
85
|
+
[Reid Morrison](https://github.com/reidmorrison) :: @reidmorrison
|
86
|
+
|
87
|
+
## License
|
88
|
+
|
89
|
+
Copyright 2012, 2013, 2014 Reid Morrison
|
90
|
+
|
91
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
92
|
+
you may not use this file except in compliance with the License.
|
93
|
+
You may obtain a copy of the License at
|
94
|
+
|
95
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
96
|
+
|
97
|
+
Unless required by applicable law or agreed to in writing, software
|
98
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
99
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
100
|
+
See the License for the specific language governing permissions and
|
101
|
+
limitations under the License.
|
data/Rakefile
ADDED
@@ -0,0 +1,28 @@
|
|
1
|
+
require 'rake/clean'
|
2
|
+
require 'rake/testtask'
|
3
|
+
|
4
|
+
$LOAD_PATH.unshift File.expand_path("../lib", __FILE__)
|
5
|
+
require 'net/tcp_client/version'
|
6
|
+
|
7
|
+
task :gem do
|
8
|
+
system "gem build net_tcp_client.gemspec"
|
9
|
+
end
|
10
|
+
|
11
|
+
task :publish => :gem do
|
12
|
+
system "git tag -a v#{Net::TCPClient::VERSION} -m 'Tagging #{Net::TCPClient::VERSION}'"
|
13
|
+
system "git push --tags"
|
14
|
+
system "gem push net_tcp_client-#{Net::TCPClient::VERSION}.gem"
|
15
|
+
system "rm net_tcp_client-#{Net::TCPClient::VERSION}.gem"
|
16
|
+
end
|
17
|
+
|
18
|
+
desc "Run Test Suite"
|
19
|
+
task :test do
|
20
|
+
Rake::TestTask.new(:functional) do |t|
|
21
|
+
t.test_files = FileList['test/*_test.rb']
|
22
|
+
t.verbose = true
|
23
|
+
end
|
24
|
+
|
25
|
+
Rake::Task['functional'].invoke
|
26
|
+
end
|
27
|
+
|
28
|
+
task :default => :test
|
@@ -0,0 +1,35 @@
|
|
1
|
+
require 'socket'
|
2
|
+
module Net
|
3
|
+
class TCPClient
|
4
|
+
|
5
|
+
class ConnectionTimeout < ::SocketError; end
|
6
|
+
class ReadTimeout < ::SocketError; end
|
7
|
+
|
8
|
+
# Raised by ResilientSocket whenever a Socket connection failure has occurred
|
9
|
+
class ConnectionFailure < ::SocketError
|
10
|
+
# Returns the hostname and port against which the connection failure occurred
|
11
|
+
attr_reader :server
|
12
|
+
|
13
|
+
# Returns the original exception that caused the connection failure
|
14
|
+
# For example instances of Errno::ECONNRESET
|
15
|
+
attr_reader :cause
|
16
|
+
|
17
|
+
# Parameters
|
18
|
+
# message [String]
|
19
|
+
# Text message of the reason for the failure and/or where it occurred
|
20
|
+
#
|
21
|
+
# server [String]
|
22
|
+
# Hostname and port
|
23
|
+
# For example: "localhost:2000"
|
24
|
+
#
|
25
|
+
# cause [Exception]
|
26
|
+
# Original Exception if any, otherwise nil
|
27
|
+
def initialize(message, server, cause=nil)
|
28
|
+
@server = server
|
29
|
+
@cause = cause
|
30
|
+
super(message)
|
31
|
+
end
|
32
|
+
end
|
33
|
+
|
34
|
+
end
|
35
|
+
end
|
@@ -0,0 +1,191 @@
|
|
1
|
+
module Net
|
2
|
+
class TCPClient
|
3
|
+
#
|
4
|
+
# Purpose: Support SemanticLogger API without forcing a dependency on SemanticLogger
|
5
|
+
#
|
6
|
+
# This Mix-in has been copied from semantic_logger/compatible
|
7
|
+
#
|
8
|
+
# Do not modify this file, grab the latest version from Semantic Logger
|
9
|
+
#
|
10
|
+
module Logging
|
11
|
+
def self.new_logger(logger=nil, name=nil, log_level=nil)
|
12
|
+
# SemanticLogger is a soft dependency, use it if already loaded
|
13
|
+
if defined?(SemanticLogger)
|
14
|
+
SemanticLogger::Logger.new(name, log_level)
|
15
|
+
elsif logger && !logger.respond_to?(:benchmark_trace)
|
16
|
+
logger.extend(InstanceMethods)
|
17
|
+
logger
|
18
|
+
else
|
19
|
+
# Return a nil logger
|
20
|
+
require 'logger'
|
21
|
+
logger = Logger.new($null)
|
22
|
+
logger.level = Logger::FATAL
|
23
|
+
logger.extend(InstanceMethods)
|
24
|
+
logger
|
25
|
+
end
|
26
|
+
end
|
27
|
+
|
28
|
+
module InstanceMethods
|
29
|
+
# See SemanticLogger for details on these logging extensions
|
30
|
+
[:debug, :info, :warn, :error, :fatal].each_with_index do |level|
|
31
|
+
class_eval <<-EOT, __FILE__, __LINE__ + 1
|
32
|
+
def #{level}(message=nil, payload=nil, exception=nil, &block)
|
33
|
+
if #{level}?
|
34
|
+
super(format_log_message('#{level}', message, payload, exception, &block))
|
35
|
+
true
|
36
|
+
else
|
37
|
+
false
|
38
|
+
end
|
39
|
+
end
|
40
|
+
|
41
|
+
def benchmark_#{level}(message, params = {}, &block)
|
42
|
+
if #{level}?
|
43
|
+
benchmark(:#{level}, message, params, &block)
|
44
|
+
else
|
45
|
+
block.call(params) if block
|
46
|
+
end
|
47
|
+
end
|
48
|
+
EOT
|
49
|
+
end
|
50
|
+
|
51
|
+
# Log trace level messages as debug
|
52
|
+
def trace(*args)
|
53
|
+
debug(*args)
|
54
|
+
end
|
55
|
+
|
56
|
+
def trace?
|
57
|
+
debug?
|
58
|
+
end
|
59
|
+
|
60
|
+
def trace_benchmark(*args)
|
61
|
+
debug_benchmark(*args)
|
62
|
+
end
|
63
|
+
|
64
|
+
def format_log_message(level, message=nil, payload=nil, exception=nil, duration=nil, &block)
|
65
|
+
if exception.nil? && payload && payload.is_a?(Exception)
|
66
|
+
exception = payload
|
67
|
+
payload = nil
|
68
|
+
end
|
69
|
+
|
70
|
+
if block && (result = block.call)
|
71
|
+
if result.is_a?(String)
|
72
|
+
message = message.nil? ? result : "\#{message} -- \#{result}"
|
73
|
+
elsif payload && payload.respond_to?(:merge)
|
74
|
+
payload.merge(result)
|
75
|
+
else
|
76
|
+
payload = result
|
77
|
+
end
|
78
|
+
end
|
79
|
+
|
80
|
+
# Add scoped payload
|
81
|
+
if self.payload
|
82
|
+
payload = payload.nil? ? self.payload : self.payload.merge(payload)
|
83
|
+
end
|
84
|
+
|
85
|
+
tags_str = tags.collect { |tag| "[#{tag}]" }.join(" ") + " " if tags && (tags.size > 0)
|
86
|
+
|
87
|
+
message = message.to_s.dup
|
88
|
+
message << " -- " << payload.inspect if payload
|
89
|
+
message << " -- Exception: " << "#{exception.class}: #{exception.message}\n#{(exception.backtrace || []).join("\n")}" if exception
|
90
|
+
|
91
|
+
duration_str = duration ? "(#{'%.1f' % duration}ms) " : ''
|
92
|
+
|
93
|
+
"#{tags_str}#{duration_str} #{message}"
|
94
|
+
end
|
95
|
+
|
96
|
+
# Measure the supplied block and log the message
|
97
|
+
def benchmark(level, message, params, &block)
|
98
|
+
start = Time.now
|
99
|
+
begin
|
100
|
+
rc = block.call(params) if block
|
101
|
+
exception = params[:exception]
|
102
|
+
rc
|
103
|
+
rescue Exception => exc
|
104
|
+
exception = exc
|
105
|
+
ensure
|
106
|
+
end_time = Time.now
|
107
|
+
# Extract options after block completes so that block can modify any of the options
|
108
|
+
log_exception = params[:log_exception] || :partial
|
109
|
+
on_exception_level = params[:on_exception_level]
|
110
|
+
min_duration = params[:min_duration] || 0.0
|
111
|
+
payload = params[:payload]
|
112
|
+
metric = params[:metric]
|
113
|
+
duration = if block_given?
|
114
|
+
1000.0 * (end_time - start)
|
115
|
+
else
|
116
|
+
params[:duration] || raise("Mandatory block missing when :duration option is not supplied")
|
117
|
+
end
|
118
|
+
|
119
|
+
# Add scoped payload
|
120
|
+
if self.payload
|
121
|
+
payload = payload.nil? ? self.payload : self.payload.merge(payload)
|
122
|
+
end
|
123
|
+
if exception
|
124
|
+
logged_exception = exception
|
125
|
+
case log_exception
|
126
|
+
when :full
|
127
|
+
# On exception change the log level
|
128
|
+
level = on_exception_level if on_exception_level
|
129
|
+
when :partial
|
130
|
+
# On exception change the log level
|
131
|
+
level = on_exception_level if on_exception_level
|
132
|
+
message = "#{message} -- Exception: #{exception.class}: #{exception.message}"
|
133
|
+
logged_exception = nil
|
134
|
+
else
|
135
|
+
logged_exception = nil
|
136
|
+
end
|
137
|
+
send(level, format_log_message(level, message, payload, logged_exception, duration, &block))
|
138
|
+
raise exception
|
139
|
+
elsif duration >= min_duration
|
140
|
+
# Only log if the block took longer than 'min_duration' to complete
|
141
|
+
send(level, format_log_message(level, message, payload, logged_exception, duration, &block))
|
142
|
+
end
|
143
|
+
end
|
144
|
+
end
|
145
|
+
|
146
|
+
def tagged(*tags)
|
147
|
+
new_tags = push_tags(*tags)
|
148
|
+
yield self
|
149
|
+
ensure
|
150
|
+
pop_tags(new_tags.size)
|
151
|
+
end
|
152
|
+
|
153
|
+
# Previous method for supplying tags
|
154
|
+
alias_method :with_tags, :tagged
|
155
|
+
|
156
|
+
def tags
|
157
|
+
# Since tags are stored on a per thread basis this list is thread-safe
|
158
|
+
t = Thread.current[:semantic_logger_tags]
|
159
|
+
t.nil? ? [] : t.clone
|
160
|
+
end
|
161
|
+
|
162
|
+
def push_tags *tags
|
163
|
+
# Need to flatten and reject empties to support calls from Rails 4
|
164
|
+
new_tags = tags.flatten.collect(&:to_s).reject(&:empty?)
|
165
|
+
t = Thread.current[:semantic_logger_tags]
|
166
|
+
Thread.current[:semantic_logger_tags] = t.nil? ? new_tags : t.concat(new_tags)
|
167
|
+
new_tags
|
168
|
+
end
|
169
|
+
|
170
|
+
def pop_tags(quantity=1)
|
171
|
+
t = Thread.current[:semantic_logger_tags]
|
172
|
+
t.pop(quantity) unless t.nil?
|
173
|
+
end
|
174
|
+
|
175
|
+
def with_payload(payload)
|
176
|
+
current_payload = self.payload
|
177
|
+
Thread.current[:semantic_logger_payload] = current_payload ? current_payload.merge(payload) : payload
|
178
|
+
yield
|
179
|
+
ensure
|
180
|
+
Thread.current[:semantic_logger_payload] = current_payload
|
181
|
+
end
|
182
|
+
|
183
|
+
def payload
|
184
|
+
Thread.current[:semantic_logger_payload]
|
185
|
+
end
|
186
|
+
|
187
|
+
end
|
188
|
+
end
|
189
|
+
end
|
190
|
+
|
191
|
+
end
|