code
stringlengths 26
124k
| docstring
stringlengths 23
125k
| func_name
stringlengths 1
98
| language
stringclasses 1
value | repo
stringlengths 5
53
| path
stringlengths 7
151
| url
stringlengths 50
211
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def log_internal_error( err )
log_internal(-2) { err }
raise err if ::Logging.raise_errors?
end
|
Internal logging method for handling exceptions. If the
`Thread#abort_on_exception` flag is set then the
exception will be raised again.
|
log_internal_error
|
ruby
|
TwP/logging
|
lib/logging.rb
|
https://github.com/TwP/logging/blob/master/lib/logging.rb
|
MIT
|
def reset
::Logging::Repository.reset
::Logging::Appenders.reset
::Logging::ColorScheme.reset
::Logging.clear_diagnostic_contexts(true)
LEVELS.clear
LNAMES.clear
remove_instance_variable :@backtrace if defined? @backtrace
remove_instance_variable :@basepath if defined? @basepath
remove_const :MAX_LEVEL_LENGTH if const_defined? :MAX_LEVEL_LENGTH
remove_const :OBJ_FORMAT if const_defined? :OBJ_FORMAT
self.utc_offset = nil
self.cause_depth = nil
self
end
|
Reset the Logging framework to it's uninitialized state
|
reset
|
ruby
|
TwP/logging
|
lib/logging.rb
|
https://github.com/TwP/logging/blob/master/lib/logging.rb
|
MIT
|
def initialized?
const_defined? :MAX_LEVEL_LENGTH
end
|
Return +true+ if the Logging framework is initialized.
|
initialized?
|
ruby
|
TwP/logging
|
lib/logging.rb
|
https://github.com/TwP/logging/blob/master/lib/logging.rb
|
MIT
|
def initialize( name, opts = {} )
::Logging.init unless ::Logging.initialized?
@name = name.to_s
@closed = false
@filters = []
@mutex = ReentrantMutex.new
self.layout = opts.fetch(:layout, ::Logging::Layouts::Basic.new)
self.level = opts.fetch(:level, nil)
self.encoding = opts.fetch(:encoding, self.encoding)
self.filters = opts.fetch(:filters, nil)
if opts.fetch(:header, true)
header = @layout.header
unless header.nil? || header.empty?
begin
write(header)
rescue StandardError => err
::Logging.log_internal_error(err)
end
end
end
::Logging::Appenders[@name] = self
end
|
call-seq:
Appender.new( name )
Appender.new( name, :layout => layout )
Creates a new appender using the given name. If no Layout is specified,
then a Basic layout will be used. Any logging header supplied by the
layout will be written to the logging destination when the Appender is
created.
Options:
:layout => the layout to use when formatting log events
:level => the level at which to log
:encoding => encoding to use when writing messages (defaults to UTF-8)
:filters => filters to apply to events before processing
|
initialize
|
ruby
|
TwP/logging
|
lib/logging/appender.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appender.rb
|
MIT
|
def append( event )
if @closed
raise RuntimeError,
"appender '<#{self.class.name}: #{@name}>' is closed"
end
# only append if the event level is less than or equal to the configured
# appender level and the filter does not disallow it
if event = allow(event)
begin
write(event)
rescue StandardError => err
::Logging.log_internal_error(err)
end
end
self
end
|
call-seq:
append( event )
Write the given _event_ to the logging destination. The log event will
be processed through the Layout associated with the Appender.
|
append
|
ruby
|
TwP/logging
|
lib/logging/appender.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appender.rb
|
MIT
|
def add_filters( *args )
args.flatten.each do |filter|
next if filter.nil?
unless filter.kind_of?(::Logging::Filter)
raise TypeError, "#{filter.inspect} is not a kind of 'Logging::Filter'"
end
@filters << filter
end
self
end
|
Sets the filter(s) to be used by this appender. The filters will be
applied in the order that they are added to the appender.
Examples
add_filters(Logging::Filters::Level.new(:warn, :error))
Returns this appender instance.
|
add_filters
|
ruby
|
TwP/logging
|
lib/logging/appender.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appender.rb
|
MIT
|
def close( footer = true )
return self if @closed
::Logging::Appenders.remove(@name)
@closed = true
flush
if footer
footer = @layout.footer
unless footer.nil? || footer.empty?
begin
write(footer)
rescue StandardError => err
::Logging.log_internal_error(err)
end
end
end
self
end
|
call-seq:
close( footer = true )
Close the appender and writes the layout footer to the logging
destination if the _footer_ flag is set to +true+. Log events will
no longer be written to the logging destination after the appender
is closed.
|
close
|
ruby
|
TwP/logging
|
lib/logging/appender.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appender.rb
|
MIT
|
def reopen
@closed = false
self
end
|
Reopen the connection to the underlying logging destination. If the
connection is currently closed then it will be opened. If the connection
is currently open then it will be closed and immediately opened.
|
reopen
|
ruby
|
TwP/logging
|
lib/logging/appender.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appender.rb
|
MIT
|
def to_s
"<%s name=\"%s\">" % [self.class.name.sub(%r/^Logging::/, ''), self.name]
end
|
call-seq:
to_s => string
Returns a string representation of the appender.
|
to_s
|
ruby
|
TwP/logging
|
lib/logging/appender.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appender.rb
|
MIT
|
def allow( event )
return nil if @level > event.level
@filters.each do |filter|
break unless event = filter.allow(event)
end
event
end
|
Check to see if the event should be processed by the appender. An event will
be rejected if the event level is lower than the configured level for the
appender. Or it will be rejected if one of the filters rejects the event.
event - The LogEvent to check
Returns the event if it is allowed; returns `nil` if it is not allowed.
|
allow
|
ruby
|
TwP/logging
|
lib/logging/appender.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appender.rb
|
MIT
|
def off?
@level >= ::Logging::LEVELS.length
end
|
Returns `true` if the appender has been turned off. This is useful for
appenders that write data to a remote location (such as syslog or email),
and that write encounters too many errors. The appender can turn itself off
to and log an error via the `Logging` logger.
Set the appender's level to a valid value to turn it back on.
|
off?
|
ruby
|
TwP/logging
|
lib/logging/appender.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appender.rb
|
MIT
|
def each( &block )
@appenders.values.each(&block)
return nil
end
|
call-seq:
each {|appender| block}
Yield each appender to the _block_.
|
each
|
ruby
|
TwP/logging
|
lib/logging/appenders.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders.rb
|
MIT
|
def reset
@color_schemes ||= {}
@color_schemes.clear
new(:default, :levels => {
:info => :green,
:warn => :yellow,
:error => :red,
:fatal => [:white, :on_red]
})
end
|
Clear all color schemes and setup a default color scheme.
|
reset
|
ruby
|
TwP/logging
|
lib/logging/color_scheme.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/color_scheme.rb
|
MIT
|
def initialize( name, opts = {} )
@scheme = Hash.new
@lines = opts.key? :lines
@levels = opts.key? :levels
raise ArgumentError, "Found both :lines and :levels - only one can be used." if lines? and levels?
lines = opts.delete :lines
levels = opts.delete :levels
load_from_hash(opts)
load_from_hash(lines) if lines?
load_from_hash(levels) if levels?
::Logging::ColorScheme[name] = self
end
|
Create a ColorScheme instance that can be accessed using the given
_name_. If a color scheme already exists with the given _name_ it will
be replaced by the new color scheme.
The color names are passed as options to the method with each name
mapping to one or more color codes. For example:
ColorScheme.new('example', :logger => [:white, :on_green], :message => :magenta)
The color codes are the lowercase names of the constants defined at the
end of this file. Multiple color codes can be aliased by grouping them
in an array as shown in the example above.
Since color schemes are primarily intended to be used with the Pattern
layout, there are a few special options of note. First the log levels
are enumerated in their own hash:
:levels => {
:debug => :blue,
:info => :cyan,
:warn => :yellow,
:error => :red,
:fatal => [:white, :on_red]
}
The log level token will be colorized differently based on the value of
the log level itself. Similarly the entire log message can be colorized
based on the value of the log level. A different option should be given
for this behavior:
:lines => {
:debug => :blue,
:info => :cyan,
:warn => :yellow,
:error => :red,
:fatal => [:white, :on_red]
}
The :levels and :lines options cannot be used together; only one or the
other should be given.
The remaining tokens defined in the Pattern layout can be colorized
using the following aliases. Their meaning in the Pattern layout are
repeated here for sake of clarity.
:logger [%c] name of the logger that generate the log event
:date [%d] datestamp
:message [%m] the user supplied log message
:pid [%p] PID of the current process
:time [%r] the time in milliseconds since the program started
:thread [%T] the name of the thread Thread.current[:name]
:thread_id [%t] object_id of the thread
:file [%F] filename where the logging request was issued
:line [%L] line number where the logging request was issued
:method [%M] method name where the logging request was issued
Please refer to the "examples/colorization.rb" file for a working
example of log colorization.
|
initialize
|
ruby
|
TwP/logging
|
lib/logging/color_scheme.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/color_scheme.rb
|
MIT
|
def load_from_hash( h )
h.each_pair do |color_tag, constants|
self[color_tag] = constants
end
end
|
Load multiple colors from key/value pairs.
|
load_from_hash
|
ruby
|
TwP/logging
|
lib/logging/color_scheme.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/color_scheme.rb
|
MIT
|
def color( string, *colors )
colors.map! { |color|
color_tag = to_key(color)
@scheme.key?(color_tag) ? @scheme[color_tag] : to_constant(color)
}
colors.compact!
return string if colors.empty?
"#{colors.join}#{string}#{CLEAR}"
end
|
This method provides easy access to ANSI color sequences, without the user
needing to remember to CLEAR at the end of each sequence. Just pass the
_string_ to color, followed by a list of _colors_ you would like it to be
affected by. The _colors_ can be ColorScheme class constants, or symbols
(:blue for BLUE, for example). A CLEAR will automatically be embedded to
the end of the returned String.
|
color
|
ruby
|
TwP/logging
|
lib/logging/color_scheme.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/color_scheme.rb
|
MIT
|
def to_constant( v )
v = v.to_s.upcase
ColorScheme.const_get(v) if (ColorScheme.const_defined?(v, false) rescue ColorScheme.const_defined?(v))
end
|
Return a normalized representation of a color setting.
|
to_constant
|
ruby
|
TwP/logging
|
lib/logging/color_scheme.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/color_scheme.rb
|
MIT
|
def delete( key )
clear_context
peek.delete(key.to_s)
end
|
Public: Remove the context value identified with the key parameter.
key - The String identifier for the context.
Returns the value associated with the key or nil if there is no value
present.
|
delete
|
ruby
|
TwP/logging
|
lib/logging/diagnostic_context.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/diagnostic_context.rb
|
MIT
|
def update( hash )
clear_context
sanitize(hash, peek)
self
end
|
Public: Add all the key/value pairs from the given hash to the current
mapped diagnostic context. The keys will be converted to strings.
Existing keys of the same name will be overwritten.
hash - The Hash of values to add to the current context.
Returns this context.
|
update
|
ruby
|
TwP/logging
|
lib/logging/diagnostic_context.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/diagnostic_context.rb
|
MIT
|
def push( hash )
clear_context
stack << sanitize(hash)
self
end
|
Public: Push a new Hash of key/value pairs onto the stack of contexts.
hash - The Hash of values to push onto the context stack.
Returns this context.
Raises an ArgumentError if hash is not a Hash.
|
push
|
ruby
|
TwP/logging
|
lib/logging/diagnostic_context.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/diagnostic_context.rb
|
MIT
|
def pop
return unless Thread.current.thread_variable_get(STACK_NAME)
return unless stack.length > 1
clear_context
stack.pop
end
|
Public: Remove the most recently pushed Hash from the stack of contexts.
If no contexts have been pushed then no action will be taken. The
default context cannot be popped off the stack; please use the `clear`
method if you want to remove all key/value pairs from the context.
Returns nil or the Hash removed from the stack.
|
pop
|
ruby
|
TwP/logging
|
lib/logging/diagnostic_context.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/diagnostic_context.rb
|
MIT
|
def clear
clear_context
Thread.current.thread_variable_set(STACK_NAME, nil)
self
end
|
Public: Clear all mapped diagnostic information if any. This method is
useful in cases where the same thread can be potentially used over and
over in different unrelated contexts.
Returns the MappedDiagnosticContext.
|
clear
|
ruby
|
TwP/logging
|
lib/logging/diagnostic_context.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/diagnostic_context.rb
|
MIT
|
def inherit( obj )
case obj
when Hash
Thread.current.thread_variable_set(STACK_NAME, [obj.dup])
when Thread
return if Thread.current == obj
DIAGNOSTIC_MUTEX.synchronize do
if hash = obj.thread_variable_get(STACK_NAME)
Thread.current.thread_variable_set(STACK_NAME, [flatten(hash)])
end
end
end
self
end
|
Public: Inherit the diagnostic context of another thread. In the vast
majority of cases the other thread will the parent that spawned the
current thread. The diagnostic context from the parent thread is cloned
before being inherited; the two diagnostic contexts can be changed
independently.
Returns the MappedDiagnosticContext.
|
inherit
|
ruby
|
TwP/logging
|
lib/logging/diagnostic_context.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/diagnostic_context.rb
|
MIT
|
def context
c = Thread.current.thread_variable_get(NAME)
if c.nil?
c = if Thread.current.thread_variable_get(STACK_NAME)
flatten(stack)
else
Hash.new
end
Thread.current.thread_variable_set(NAME, c)
end
return c
end
|
Returns the Hash acting as the storage for this MappedDiagnosticContext.
A new storage Hash is created for each Thread running in the
application.
|
context
|
ruby
|
TwP/logging
|
lib/logging/diagnostic_context.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/diagnostic_context.rb
|
MIT
|
def stack
s = Thread.current.thread_variable_get(STACK_NAME)
if s.nil?
s = [{}]
Thread.current.thread_variable_set(STACK_NAME, s)
end
return s
end
|
Returns the stack of Hash objects that are storing the diagnostic
context information. This stack is guarnteed to always contain at least
one Hash.
|
stack
|
ruby
|
TwP/logging
|
lib/logging/diagnostic_context.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/diagnostic_context.rb
|
MIT
|
def sanitize( hash, target = {} )
unless hash.is_a?(Hash)
raise ArgumentError, "Expecting a Hash but received a #{hash.class.name}"
end
hash.each { |k,v| target[k.to_s] = v }
return target
end
|
Given a Hash convert all keys into Strings. The values are not altered
in any way. The converted keys and their values are stored in the target
Hash if provided. Otherwise a new Hash is created and returned.
hash - The Hash of values to push onto the context stack.
target - The target Hash to store the key value pairs.
Returns a new Hash with all keys converted to Strings.
Raises an ArgumentError if hash is not a Hash.
|
sanitize
|
ruby
|
TwP/logging
|
lib/logging/diagnostic_context.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/diagnostic_context.rb
|
MIT
|
def flatten( ary )
return ary.first.dup if ary.length == 1
hash = {}
ary.each { |h| hash.update h }
return hash
end
|
Given an Array of Hash objects, flatten all the key/value pairs from the
Hash objects in the ary into a single Hash. The flattening occurs left
to right. So that the key/value in the very last Hash overrides any
other key from the previous Hash objcts.
ary - An Array of Hash objects.
Returns a Hash.
|
flatten
|
ruby
|
TwP/logging
|
lib/logging/diagnostic_context.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/diagnostic_context.rb
|
MIT
|
def push( message )
context.push(message)
if block_given?
begin
yield
ensure
context.pop
end
end
self
end
|
Public: Push new diagnostic context information for the current thread.
The contents of the message parameter is determined solely by the
client.
message - The message String to add to the current context.
Returns the current NestedDiagnosticContext.
|
push
|
ruby
|
TwP/logging
|
lib/logging/diagnostic_context.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/diagnostic_context.rb
|
MIT
|
def clear
Thread.current.thread_variable_set(NAME, nil)
self
end
|
Public: Clear all nested diagnostic information if any. This method is
useful in cases where the same thread can be potentially used over and
over in different unrelated contexts.
Returns the NestedDiagnosticContext.
|
clear
|
ruby
|
TwP/logging
|
lib/logging/diagnostic_context.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/diagnostic_context.rb
|
MIT
|
def inherit( obj )
case obj
when Array
Thread.current.thread_variable_set(NAME, obj.dup)
when Thread
return if Thread.current == obj
DIAGNOSTIC_MUTEX.synchronize do
Thread.current.thread_variable_set(NAME, obj.thread_variable_get(NAME).dup) if obj.thread_variable_get(NAME)
end
end
self
end
|
Public: Inherit the diagnostic context of another thread. In the vast
majority of cases the other thread will the parent that spawned the
current thread. The diagnostic context from the parent thread is cloned
before being inherited; the two diagnostic contexts can be changed
independently.
Returns the NestedDiagnosticContext.
|
inherit
|
ruby
|
TwP/logging
|
lib/logging/diagnostic_context.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/diagnostic_context.rb
|
MIT
|
def context
c = Thread.current.thread_variable_get(NAME)
if c.nil?
c = Array.new
Thread.current.thread_variable_set(NAME, c)
end
return c
end
|
Returns the Array acting as the storage stack for this
NestedDiagnosticContext. A new storage Array is created for each Thread
running in the application.
|
context
|
ruby
|
TwP/logging
|
lib/logging/diagnostic_context.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/diagnostic_context.rb
|
MIT
|
def create_with_logging_context( m, *a, &b )
mdc, ndc = nil
if Thread.current.thread_variable_get(Logging::MappedDiagnosticContext::STACK_NAME)
mdc = Logging::MappedDiagnosticContext.context.dup
end
if Thread.current.thread_variable_get(Logging::NestedDiagnosticContext::NAME)
ndc = Logging::NestedDiagnosticContext.context.dup
end
# This calls the actual `Thread#new` method to create the Thread instance.
# If your memory profiling tool says this method is leaking memory, then
# you are leaking Thread instances somewhere.
self.send(m, *a) { |*args|
Logging::MappedDiagnosticContext.inherit(mdc)
Logging::NestedDiagnosticContext.inherit(ndc)
b.call(*args)
}
end
|
In order for the diagnostic contexts to behave properly we need to
inherit state from the parent thread. The only way I have found to do
this in Ruby is to override `new` and capture the contexts from the
parent Thread at the time the child Thread is created. The code below does
just this. If there is a more idiomatic way of accomplishing this in Ruby,
please let me know!
Also, great care is taken in this code to ensure that a reference to the
parent thread does not exist in the binding associated with the block
being executed in the child thread. The same is true for the parent
thread's mdc and ndc. If any of those references end up in the binding,
then they cannot be garbage collected until the child thread exits.
|
create_with_logging_context
|
ruby
|
TwP/logging
|
lib/logging/diagnostic_context.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/diagnostic_context.rb
|
MIT
|
def initialize
::Logging.init unless ::Logging.initialized?
end
|
Creates a new level filter that will pass all log events. Create a
subclass and override the `allow` method to filter log events.
|
initialize
|
ruby
|
TwP/logging
|
lib/logging/filter.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/filter.rb
|
MIT
|
def initialize( opts = {} )
::Logging.init unless ::Logging.initialized?
default = ::Logging.const_defined?('OBJ_FORMAT') ?
::Logging::OBJ_FORMAT : nil
f = opts.fetch(:format_as, default)
f = f.intern if f.instance_of? String
@obj_format = case f
when :inspect, :yaml, :json; f
else :string end
self.backtrace = opts.fetch(:backtrace, ::Logging.backtrace)
self.utc_offset = opts.fetch(:utc_offset, ::Logging.utc_offset)
self.cause_depth = opts.fetch(:cause_depth, ::Logging.cause_depth)
end
|
call-seq:
Layout.new( :format_as => :string )
Creates a new layout that will format objects as strings using the
given <tt>:format_as</tt> style. This can be one of <tt>:string</tt>,
<tt>:inspect</tt>, or <tt>:yaml</tt>. These formatting commands map to
the following object methods:
* :string => to_s
* :inspect => inspect
* :yaml => to_yaml
* :json => MultiJson.encode(obj)
If the format is not specified then the global object format is used
(see Logging#format_as). If the global object format is not specified
then <tt>:string</tt> is used.
|
initialize
|
ruby
|
TwP/logging
|
lib/logging/layout.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/layout.rb
|
MIT
|
def apply_utc_offset( time )
return time if utc_offset.nil?
time = time.dup
if utc_offset == 0
time.utc
else
time.localtime(utc_offset)
end
time
end
|
Internal: Helper method that applies the UTC offset to the given `time`
instance. A new Time is returned that is equivalent to the original `time`
but pinned to the timezone given by the UTC offset.
If a UTC offset has not been set, then the original `time` instance is
returned unchanged.
|
apply_utc_offset
|
ruby
|
TwP/logging
|
lib/logging/layout.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/layout.rb
|
MIT
|
def format_obj( obj )
case obj
when String; obj
when Exception
lines = ["<#{obj.class.name}> #{obj.message}"]
lines.concat(obj.backtrace) if backtrace? && obj.backtrace
format_cause(obj, lines)
lines.join("\n\t")
when nil; "<#{obj.class.name}> nil"
else
str = "<#{obj.class.name}> "
str << case @obj_format
when :inspect; obj.inspect
when :yaml; try_yaml(obj)
when :json; try_json(obj)
else obj.to_s end
str
end
end
|
call-seq:
format_obj( obj )
Return a string representation of the given object. Depending upon
the configuration of the logger system the format will be an +inspect+
based representation or a +yaml+ based representation.
|
format_obj
|
ruby
|
TwP/logging
|
lib/logging/layout.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/layout.rb
|
MIT
|
def format_cause(e, lines)
return lines if cause_depth == 0
cause_depth.times do
break unless e.respond_to?(:cause) && e.cause
cause = e.cause
lines << "--- Caused by ---"
lines << "<#{cause.class.name}> #{cause.message}"
lines.concat(format_cause_backtrace(e, cause)) if backtrace? && cause.backtrace
e = cause
end
if e.respond_to?(:cause) && e.cause
lines << "--- Further #cause backtraces were omitted ---"
end
lines
end
|
Internal: Format any nested exceptions found in the given exception `e`
while respecting the maximum `cause_depth`. The lines array is used to
capture all the output lines form the nested exceptions; the array is later
joined by the `format_obj` method.
e - Exception to format
lines - Array of output lines
Returns the input `lines` Array
|
format_cause
|
ruby
|
TwP/logging
|
lib/logging/layout.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/layout.rb
|
MIT
|
def format_cause_backtrace(e, cause)
# Find where the cause's backtrace differs from the parent exception's.
backtrace = Array(e.backtrace)
cause_backtrace = Array(cause.backtrace)
index = -1
min_index = [backtrace.size, cause_backtrace.size].min * -1
just_in_case = -5000
while index > min_index && backtrace[index] == cause_backtrace[index] && index >= just_in_case
index -= 1
end
# Add on a few common frames to make it clear where the backtraces line up.
index += 3
index = -1 if index >= 0
cause_backtrace[0..index]
end
|
Internal: Format the backtrace of the nested `cause` but remove the common
exception lines from the parent exception. This helps keep the backtraces a
wee bit shorter and more comprehensible.
e - parent exception
cause - the nested exception generating the returned backtrace
Returns an Array of backtracke lines.
|
format_cause_backtrace
|
ruby
|
TwP/logging
|
lib/logging/layout.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/layout.rb
|
MIT
|
def try_yaml( obj )
"\n#{obj.to_yaml}"
rescue TypeError
obj.inspect
end
|
Attempt to format the _obj_ using yaml, but fall back to inspect style
formatting if yaml fails.
obj - The Object to format.
Returns a String representation of the object.
|
try_yaml
|
ruby
|
TwP/logging
|
lib/logging/layout.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/layout.rb
|
MIT
|
def try_json( obj )
MultiJson.encode(obj)
rescue StandardError
obj.inspect
end
|
Attempt to format the given object as a JSON string, but fall back to
inspect formatting if JSON encoding fails.
obj - The Object to format.
Returns a String representation of the object.
|
try_json
|
ruby
|
TwP/logging
|
lib/logging/layout.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/layout.rb
|
MIT
|
def initialize( name )
case name
when String
raise(ArgumentError, "logger must have a name") if name.empty?
else raise(ArgumentError, "logger name must be a String") end
repo = ::Logging::Repository.instance
_setup(name, :parent => repo.parent(name))
end
|
call-seq:
Logger.new( name )
Logger[name]
Returns the logger identified by _name_.
When _name_ is a +String+ or a +Symbol+ it will be used "as is" to
retrieve the logger. When _name_ is a +Class+ the class name will be
used to retrieve the logger. When _name_ is an object the name of the
object's class will be used to retrieve the logger.
Example:
obj = MyClass.new
log1 = Logger.new(obj)
log2 = Logger.new(MyClass)
log3 = Logger['MyClass']
log1.object_id == log2.object_id # => true
log2.object_id == log3.object_id # => true
|
initialize
|
ruby
|
TwP/logging
|
lib/logging/logger.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/logger.rb
|
MIT
|
def add( lvl, data = nil, progname = nil )
lvl = Integer(lvl)
return false if lvl < level
if data.nil?
if block_given?
data = yield
else
data = progname
end
end
log_event(::Logging::LogEvent.new(@name, lvl, data, @caller_tracing))
true
end
|
call-seq:
add( severity, message = nil ) {block}
Log a message if the given severity is high enough. This is the generic
logging method. Users will be more inclined to use #debug, #info, #warn,
#error, and #fatal.
<b>Message format</b>: +message+ can be any object, but it has to be
converted to a String in order to log it. The Logging::format_as
method is used to determine how objects chould be converted to
strings. Generally, +inspect+ is used.
A special case is an +Exception+ object, which will be printed in
detail, including message, class, and backtrace.
If a _message_ is not given, then the return value from the block is
used as the message to log. This is useful when creating the actual
message is an expensive operation. This allows the logger to check the
severity against the configured level before actually constructing the
message.
This method returns +true+ if the message was logged, and +false+ is
returned if the message was not logged.
|
add
|
ruby
|
TwP/logging
|
lib/logging/logger.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/logger.rb
|
MIT
|
def level
return @level unless @level.nil?
@parent.level
end
|
call-seq:
level => integer
Returns an integer which is the defined log level for this logger.
|
level
|
ruby
|
TwP/logging
|
lib/logging/logger.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/logger.rb
|
MIT
|
def add_appenders( *args )
args.flatten.each do |arg|
o = arg.kind_of?(::Logging::Appender) ? arg : ::Logging::Appenders[arg.to_s]
raise ArgumentError, "unknown appender #{arg.inspect}" if o.nil?
@appenders << o unless @appenders.include?(o)
end
self
end
|
call-seq:
add_appenders( appenders )
Add the given _appenders_ to the list of appenders, where _appenders_
can be either a single appender or an array of appenders.
|
add_appenders
|
ruby
|
TwP/logging
|
lib/logging/logger.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/logger.rb
|
MIT
|
def remove_appenders( *args )
args.flatten.each do |arg|
@appenders.delete_if do |a|
case arg
when String; arg == a.name
when ::Logging::Appender; arg.object_id == a.object_id
else
raise ArgumentError, "#{arg.inspect} is not a 'Logging::Appender'"
end
end
end
self
end
|
call-seq:
remove_appenders( appenders )
Remove the given _appenders_ from the list of appenders. The appenders
to remove can be identified either by name using a +String+ or by
passing the appender instance. _appenders_ can be a single appender or
an array of appenders.
|
remove_appenders
|
ruby
|
TwP/logging
|
lib/logging/logger.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/logger.rb
|
MIT
|
def log_event( event )
@appenders.each {|a| a.append(event)}
@parent.log_event(event) if @additive
end
|
call-seq:
log_event( event )
Send the given _event_ to the appenders for logging, and pass the
_event_ up to the parent if additive mode is enabled. The log level has
already been checked before this method is called.
|
log_event
|
ruby
|
TwP/logging
|
lib/logging/logger.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/logger.rb
|
MIT
|
def define_log_methods( force = false, code = nil )
return if has_own_level? and !force
::Logging::Logger.mutex.synchronize do
::Logging::Logger.define_log_methods(self)
::Logging::Repository.instance.children(name).each do |child|
child.define_log_methods
end
end
self
end
|
call-seq:
define_log_methods( force = false )
Define the logging methods for this logger based on the configured log
level. If the level is nil, then we will ask our parent for it's level
and define log levels accordingly. The force flag will skip this
check.
Recursively call this method on all our children loggers.
|
define_log_methods
|
ruby
|
TwP/logging
|
lib/logging/logger.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/logger.rb
|
MIT
|
def _meta_eval( code, file = nil, line = nil )
meta = class << self; self end
meta.class_eval code, file, line
end
|
call-seq:
_meta_eval( code )
Evaluates the given string of _code_ if the singleton class of this
Logger object.
|
_meta_eval
|
ruby
|
TwP/logging
|
lib/logging/logger.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/logger.rb
|
MIT
|
def _setup( name, opts = {} )
@name = name
@parent = opts.fetch(:parent, nil)
@appenders = opts.fetch(:appenders, [])
@additive = opts.fetch(:additive, true)
@level = opts.fetch(:level, nil)
@caller_tracing = opts.fetch(:caller_tracing, false)
::Logging::Logger.define_log_methods(self)
end
|
call-seq:
_setup( name, opts = {} )
Configures internal variables for the logger. This method can be used
to avoid storing the logger in the repository.
|
_setup
|
ruby
|
TwP/logging
|
lib/logging/logger.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/logger.rb
|
MIT
|
def _dump_configuration( indent = 0 )
str, spacer, base = '', ' ', 50
indent_str = indent == 0 ? '' : ' ' * indent
str << indent_str
str << self.name.shrink(base - indent)
if (str.length + spacer.length) < base
str << spacer
str << '.' * (base - str.length)
end
str = str.ljust(base)
str << spacer
level_str = @level.nil? ? '' : '*'
level_str << if level < ::Logging::LEVELS.length
::Logging.levelify(::Logging::LNAMES[level])
else
'off'
end
level_len = ::Logging::MAX_LEVEL_LENGTH + 1
str << sprintf("%#{level_len}s" % level_str)
str << spacer
if self.respond_to?(:additive)
str << (additive ? '+A' : '-A')
else
str << ' '
end
str << spacer
str << (caller_tracing ? '+T' : '-T')
str << "\n"
@appenders.each do |appender|
str << indent_str
str << '- '
str << appender.to_s
str << "\n"
end
return str
end
|
call-seq:
_dump_configuration( io = STDOUT, indent = 0 )
An internal method that is used to dump this logger's configuration to
the given _io_ stream. The configuration includes the logger's name,
level, additivity, and caller_tracing settings. The configured appenders
are also printed to the _io_ stream.
|
_dump_configuration
|
ruby
|
TwP/logging
|
lib/logging/logger.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/logger.rb
|
MIT
|
def initialize( logger, level, data, caller_tracing )
self.logger = logger
self.level = level
self.data = data
self.time = Time.now.freeze
if caller_tracing
stack = Kernel.caller[CALLER_INDEX]
return if stack.nil?
match = CALLER_RGXP.match(stack)
self.file = match[1]
self.line = Integer(match[2])
self.method_name = match[3] unless match[3].nil?
if (bp = ::Logging.basepath) && !bp.empty? && file.index(bp) == 0
self.file = file.slice(bp.length + 1, file.length - bp.length)
end
else
self.file = self.line = self.method_name = ''
end
end
|
call-seq:
LogEvent.new( logger, level, [data], caller_tracing )
Creates a new log event with the given _logger_ name, numeric _level_,
array of _data_ from the user to be logged, and boolean _caller_tracing_ flag.
If the _caller_tracing_ flag is set to +true+ then Kernel::caller will be
invoked to get the execution trace of the logging method.
|
initialize
|
ruby
|
TwP/logging
|
lib/logging/log_event.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/log_event.rb
|
MIT
|
def initialize( object, &block )
Kernel.raise ArgumentError, "Cannot proxy nil" if nil.equal? object
@object = object
@leader = @object.is_a?(Class) ? "#{@object.name}." : "#{@object.class.name}#"
@logger = Logging.logger[object]
if block
eigenclass = class << self; self; end
eigenclass.__send__(:define_method, :method_missing, &block)
end
end
|
:startdoc:
Create a new proxy for the given _object_. If an optional _block_ is
given it will be called before the proxied method. This _block_ will
replace the +method_missing+ implementation
|
initialize
|
ruby
|
TwP/logging
|
lib/logging/proxy.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/proxy.rb
|
MIT
|
def method_missing( name, *args, &block )
@logger << "#@leader#{name}(#{args.inspect[1..-2]})\n"
@object.send(name, *args, &block)
end
|
All hail the magic of method missing. Here is where we are going to log
the method call and then forward to the proxied object. The return value
from the proxied object method call is passed back.
|
method_missing
|
ruby
|
TwP/logging
|
lib/logging/proxy.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/proxy.rb
|
MIT
|
def silence( *args )
yield self
end
|
A no-op implementation of the +silence+ method. Setting of log levels
should be done during the Logging configuration. It is the author's
opinion that overriding the log level programmatically is a logical
error.
Please see https://github.com/TwP/logging/issues/11 for a more detailed
discussion of the issue.
|
silence
|
ruby
|
TwP/logging
|
lib/logging/rails_compat.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/rails_compat.rb
|
MIT
|
def initialize
@h = {:root => ::Logging::RootLogger.new}
# configures the internal logger which is disabled by default
logger = ::Logging::Logger.allocate
logger._setup(
to_key(::Logging),
:parent => @h[:root],
:additive => false,
:level => ::Logging::LEVELS.length # turns this logger off
)
@h[logger.name] = logger
end
|
nodoc:
This is a singleton class -- use the +instance+ method to obtain the
+Repository+ instance.
|
initialize
|
ruby
|
TwP/logging
|
lib/logging/repository.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/repository.rb
|
MIT
|
def delete( key )
key = to_key(key)
raise 'the :root logger cannot be deleted' if :root == key
parent = @h.fetch(key).parent
children(key).each {|c| c.__send__(:parent=, parent)}
@h.delete(key)
end
|
call-seq:
delete( name )
Deletes the named logger from the repository. All direct children of the
logger will have their parent reassigned. So the parent of the logger
being deleted becomes the new parent of the children.
When _name_ is a +String+ or a +Symbol+ it will be used "as is" to
remove the logger. When _name_ is a +Class+ the class name will be
used to remove the logger. When _name_ is an object the name of the
object's class will be used to remove the logger.
Raises a RuntimeError if you try to delete the root logger.
Raises an KeyError if the named logger is not found.
|
delete
|
ruby
|
TwP/logging
|
lib/logging/repository.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/repository.rb
|
MIT
|
def parent( key )
name = parent_name(to_key(key))
return if name.nil?
@h[name]
end
|
call-seq:
parent( key )
Returns the parent logger for the logger identified by _key_ where
_key_ follows the same identification rules described in
<tt>Repository#[]</tt>. A parent is returned regardless of the
existence of the logger referenced by _key_.
A note about parents -
If you have a class A::B::C, then the parent of C is B, and the parent
of B is A. Parents are determined by namespace.
|
parent
|
ruby
|
TwP/logging
|
lib/logging/repository.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/repository.rb
|
MIT
|
def children( parent )
ary = []
parent = to_key(parent)
@h.each_pair do |child,logger|
next if :root == child
ary << logger if parent == parent_name(child)
end
return ary.sort
end
|
call-seq:
children( key )
Returns an array of the children loggers for the logger identified by
_key_ where _key_ follows the same identification rules described in
+Repository#[]+. Children are returned regardless of the
existence of the logger referenced by _key_.
|
children
|
ruby
|
TwP/logging
|
lib/logging/repository.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/repository.rb
|
MIT
|
def to_key( key )
case key
when :root, 'root'; :root
when String; key
when Symbol; key.to_s
when Module; key.logger_name
when Object; key.class.logger_name
end
end
|
call-seq:
to_key( key )
Takes the given _key_ and converts it into a form that can be used to
retrieve a logger from the +Repository+ hash.
When _key_ is a +String+ or a +Symbol+ it will be returned "as is".
When _key_ is a +Class+ the class name will be returned. When _key_ is
an object the name of the object's class will be returned.
|
to_key
|
ruby
|
TwP/logging
|
lib/logging/repository.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/repository.rb
|
MIT
|
def parent_name( key )
return if :root == key
a = key.split PATH_DELIMITER
p = :root
while a.slice!(-1) and !a.empty?
k = a.join PATH_DELIMITER
if @h.has_key? k then p = k; break end
end
p
end
|
Returns the name of the parent for the logger identified by the given
_key_. If the _key_ is for the root logger, then +nil+ is returned.
|
parent_name
|
ruby
|
TwP/logging
|
lib/logging/repository.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/repository.rb
|
MIT
|
def initialize( )
::Logging.init unless ::Logging.initialized?
@name = 'root'
@appenders = []
@additive = false
@caller_tracing = false
@level = 0
::Logging::Logger.define_log_methods(self)
end
|
call-seq:
RootLogger.new
Returns a new root logger instance. This method will be called only
once when the +Repository+ singleton instance is created.
|
initialize
|
ruby
|
TwP/logging
|
lib/logging/root_logger.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/root_logger.rb
|
MIT
|
def shrink( width, ellipses = '...')
raise ArgumentError, "width cannot be negative: #{width}" if width < 0
return self if length <= width
remove = length - width + ellipses.length
return ellipses.dup if remove >= length
left_end = (length + 1 - remove) / 2
right_start = left_end + remove
left = self[0,left_end]
right = self[right_start,length-right_start]
left << ellipses << right
end
|
call-seq:
shrink( width, ellipses = '...' ) #=> string
Shrink the size of the current string to the given _width_ by removing
characters from the middle of the string and replacing them with
_ellipses_. If the _width_ is greater than the length of the string, the
string is returned unchanged. If the _width_ is less than the length of
the _ellipses_, then the _ellipses_ are returned.
|
shrink
|
ruby
|
TwP/logging
|
lib/logging/utils.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/utils.rb
|
MIT
|
def logger_name
return name unless name.nil? or name.empty?
# check if this is a metaclass (or eigenclass)
if ancestors.include? Class
inspect =~ %r/#<Class:([^#>]+)>/
return $1
end
# see if we have a superclass
if respond_to? :superclass
return superclass.logger_name
end
# we are an anonymous module
::Logging.log_internal(-2) {
'cannot return a predictable, unique name for anonymous modules'
}
return 'anonymous'
end
|
call-seq:
logger_name #=> string
Returns a predictable logger name for the current module or class. If
used within an anonymous class, the first non-anonymous class name will
be used as the logger name. If used within a meta-class, the name of the
actual class will be used as the logger name. If used within an
anonymous module, the string 'anonymous' will be returned.
|
logger_name
|
ruby
|
TwP/logging
|
lib/logging/utils.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/utils.rb
|
MIT
|
def flock?
status = flock(LOCK_EX|LOCK_NB)
case status
when false; true
when 0; block_given? ? yield : false
else
raise SystemCallError, "flock failed with status: #{status}"
end
ensure
flock LOCK_UN
end
|
Returns <tt>true</tt> if another process holds an exclusive lock on the
file. Returns <tt>false</tt> if this is not the case.
If a <tt>block</tt> of code is passed to this method, it will be run iff
this process can obtain an exclusive lock on the file. The block will be
run while this lock is held, and the exclusive lock will be released when
the method returns.
The exclusive lock is requested in a non-blocking mode. This method will
return immediately (and the block will not be executed) if an exclusive
lock cannot be obtained.
|
flock?
|
ruby
|
TwP/logging
|
lib/logging/utils.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/utils.rb
|
MIT
|
def flock_sh
flock LOCK_SH
yield
ensure
flock LOCK_UN
end
|
Execute a <tt>block</tt> in the context of a shared lock on this file. A
shared lock will be obtained on the file, the block executed, and the lock
released.
|
flock_sh
|
ruby
|
TwP/logging
|
lib/logging/utils.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/utils.rb
|
MIT
|
def concat( src, dest )
if File.exist?(dest)
bufsize = File.stat(dest).blksize || 8192
buffer = String.new
File.open(dest, 'a') { |d|
File.open(src, 'r') { |r|
while bytes = r.read(bufsize, buffer)
d.syswrite bytes
end
}
}
else
copy_file(src, dest)
end
end
|
Concatenate the contents of the _src_ file to the end of the _dest_ file.
If the _dest_ file does not exist, then the _src_ file is copied to the
_dest_ file using +copy_file+.
|
concat
|
ruby
|
TwP/logging
|
lib/logging/utils.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/utils.rb
|
MIT
|
def initialize( *args, &block )
@buffer = []
@immediate = []
@auto_flushing = 1
@async = false
@flush_period = @async_flusher = nil
super(*args, &block)
end
|
Setup the message buffer and other variables for automatically and
periodically flushing the buffer.
|
initialize
|
ruby
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/buffering.rb
|
MIT
|
def close( *args )
flush
if @async_flusher
@async_flusher.stop
@async_flusher = nil
Thread.pass
end
super(*args)
end
|
Close the message buffer by flushing all log events to the appender. If an
async flusher thread is running, shut it down and allow it to exit.
|
close
|
ruby
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/buffering.rb
|
MIT
|
def reopen
_setup_async_flusher
super
end
|
Reopen the connection to the underlying logging destination. In addition
if the appender is configured for asynchronous flushing, then the flushing
thread will be stopped and restarted.
|
reopen
|
ruby
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/buffering.rb
|
MIT
|
def flush
return self if @buffer.empty?
ary = nil
@mutex.synchronize {
ary = @buffer.dup
@buffer.clear
}
if ary.length <= write_size
str = ary.join
canonical_write str unless str.empty?
else
ary.each_slice(write_size) do |a|
str = a.join
canonical_write str unless str.empty?
end
end
self
end
|
Call `flush` to force an appender to write out any buffered log events.
Similar to `IO#flush`, so use in a similar fashion.
|
flush
|
ruby
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/buffering.rb
|
MIT
|
def clear!
@mutex.synchronize { @buffer.clear }
end
|
Clear the underlying buffer of all log events. These events will not be
appended to the logging destination; they will be lost.
|
clear!
|
ruby
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/buffering.rb
|
MIT
|
def configure_buffering( opts )
::Logging.init unless ::Logging.initialized?
self.immediate_at = opts.fetch(:immediate_at, '')
self.auto_flushing = opts.fetch(:auto_flushing, true)
self.flush_period = opts.fetch(:flush_period, nil)
self.async = opts.fetch(:async, false)
self.write_size = opts.fetch(:write_size, DEFAULT_BUFFER_SIZE)
end
|
Configure the buffering using the arguments found in the give options
hash. This method must be called in order to use the message buffer.
The supported options are "immediate_at" and "auto_flushing". Please
refer to the documentation for those methods to see the allowed
options.
|
configure_buffering
|
ruby
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/buffering.rb
|
MIT
|
def immediate?( event )
return false unless event.respond_to? :level
@immediate[event.level]
end
|
Returns `true` if the `event` level matches one of the configured
immediate logging levels. Otherwise returns `false`.
|
immediate?
|
ruby
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/buffering.rb
|
MIT
|
def write( event )
str = event.instance_of?(::Logging::LogEvent) ?
layout.format(event) : event.to_s
return if str.empty?
if @auto_flushing == 1
canonical_write(str)
else
str = str.force_encoding(encoding) if encoding && str.encoding != encoding
@mutex.synchronize {
@buffer << str
}
flush_now = @buffer.length >= @auto_flushing || immediate?(event)
if flush_now
if async?
@async_flusher.signal(flush_now)
else
self.flush
end
elsif @async_flusher && flush_period?
@async_flusher.signal
end
end
self
end
|
call-seq:
write( event )
Writes the given `event` to the logging destination. The `event` can
be either a LogEvent or a String. If a LogEvent, then it will be
formatted using the layout given to the appender when it was created.
The `event` will be formatted and then buffered until the
"auto_flushing" level has been reached. At this time the canonical_write
method will be used to log all events stored in the buffer.
Returns this appender instance
|
write
|
ruby
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/buffering.rb
|
MIT
|
def _parse_hours_minutes_seconds( str )
m = %r/^\s*(\d{2,}):(\d{2}):(\d{2}(?:\.\d+)?)\s*$/.match(str)
return if m.nil?
(3600 * m[1].to_i) + (60 * m[2].to_i) + (m[3].to_f)
end
|
Attempt to parse an hours/minutes/seconds value from the string and return
an integer number of seconds.
str - The input String to parse for time values.
Examples
_parse_hours_minutes_seconds("14:12:42") #=> 51162
_parse_hours_minutes_seconds("foo") #=> nil
Returns a Numeric or `nil`
|
_parse_hours_minutes_seconds
|
ruby
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/buffering.rb
|
MIT
|
def _parse_numeric( str )
Integer(str) rescue (Float(str) rescue nil)
end
|
Convert the string into a numeric value. If the string does not
represent a valid Integer or Float then `nil` is returned.
str - The input String to parse for Numeric values.
Examples
_parse_numeric("10") #=> 10
_parse_numeric("1.0") #=> 1.0
_parse_numeric("foo") #=> nil
Returns a Numeric or `nil`
|
_parse_numeric
|
ruby
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/buffering.rb
|
MIT
|
def _setup_async_flusher
# stop and remove any existing async flusher instance
if @async_flusher
@async_flusher.stop
@async_flusher = nil
Thread.pass
end
# create a new async flusher if we have a valid flush period
if @flush_period || async?
@auto_flushing = DEFAULT_BUFFER_SIZE unless @auto_flushing > 1
@async_flusher = AsyncFlusher.new(self, @flush_period)
@async_flusher.start
Thread.pass
end
nil
end
|
Using the flush_period, create a new AsyncFlusher attached to this
appender. If the flush_period is nil, then no action will be taken. If a
AsyncFlusher already exists, it will be stopped and a new one will be
created.
Returns `nil`
|
_setup_async_flusher
|
ruby
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/buffering.rb
|
MIT
|
def initialize( appender, period )
@appender = appender
@period = period
@mutex = Mutex.new
@cv = ConditionVariable.new
@thread = nil
@waiting = nil
@signaled = false
@immediate = 0
end
|
Create a new AsyncFlusher instance that will call the `flush`
method on the given `appender`. The `flush` method will be called
every `period` seconds, but only when the message buffer is non-empty.
appender - The Appender instance to periodically `flush`
period - The Numeric sleep period or `nil`
|
initialize
|
ruby
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/buffering.rb
|
MIT
|
def start
return if @thread
@thread = Thread.new { loop {
begin
break if Thread.current[:stop]
_wait_for_signal
_try_to_sleep
@appender.flush
rescue => err
::Logging.log_internal {"AsyncFlusher for appender #{@appender.inspect} encountered an error"}
::Logging.log_internal_error(err)
end
}}
self
end
|
Start the periodic flusher's internal run loop.
Returns this flusher instance
|
start
|
ruby
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/buffering.rb
|
MIT
|
def stop
return if @thread.nil?
@thread[:stop] = true
signal if waiting?
@thread = nil
self
end
|
Stop the async flusher's internal run loop.
Returns this flusher instance
|
stop
|
ruby
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/buffering.rb
|
MIT
|
def signal( immediate = nil )
return if Thread.current == @thread # don't signal ourselves
return if @signaled # don't need to signal again
@mutex.synchronize {
@signaled = true
@immediate += 1 if immediate
@cv.signal
}
self
end
|
Signal the async flusher. This will wake up the run loop if it is
currently waiting for something to do. If the signal method is never
called, the async flusher will never perform the flush action on
the appender.
immediate - Set to `true` if the sleep period should be skipped
Returns this flusher instance
|
signal
|
ruby
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/buffering.rb
|
MIT
|
def immediate?
@immediate > 0
end
|
Returns `true` if the flusher should immeidately write the buffer to the
IO destination.
|
immediate?
|
ruby
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/buffering.rb
|
MIT
|
def initialize( *args )
name = self.class.name.split("::").last.downcase
opts = args.last.is_a?(Hash) ? args.pop : {}
name = args.shift unless args.empty?
io = open_fd
opts[:encoding] = io.external_encoding
super(name, io, opts)
end
|
call-seq:
Stdout.new( name = 'stdout' )
Stderr.new( :layout => layout )
Stdout.new( name = 'stdout', :level => 'info' )
Creates a new Stdout/Stderr Appender. The name 'stdout'/'stderr' will be
used unless another is given. Optionally, a layout can be given for the
appender to use (otherwise a basic appender will be created) and a log
level can be specified.
Options:
:layout => the layout to use when formatting log events
:level => the level at which to log
|
initialize
|
ruby
|
TwP/logging
|
lib/logging/appenders/console.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/console.rb
|
MIT
|
def reopen
@mutex.synchronize {
flush if defined? @io && @io
@io = open_fd
}
super
self
end
|
Reopen the connection to the underlying logging destination. If the
connection is currently closed then it will be opened. If the connection
is currently open then it will be closed and immediately reopened.
|
reopen
|
ruby
|
TwP/logging
|
lib/logging/appenders/console.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/console.rb
|
MIT
|
def initialize( name, opts = {} )
@filename = opts.fetch(:filename, name)
raise ArgumentError, 'no filename was given' if @filename.nil?
@filename = ::File.expand_path(@filename).freeze
self.class.assert_valid_logfile(@filename)
self.encoding = opts.fetch(:encoding, self.encoding)
io = open_file
super(name, io, opts)
truncate if opts.fetch(:truncate, false)
end
|
call-seq:
File.new( name, :filename => 'file' )
File.new( name, :filename => 'file', :truncate => true )
File.new( name, :filename => 'file', :layout => layout )
Creates a new File Appender that will use the given filename as the
logging destination. If the file does not already exist it will be
created. If the :truncate option is set to +true+ then the file will
be truncated before writing begins; otherwise, log messages will be
appended to the file.
|
initialize
|
ruby
|
TwP/logging
|
lib/logging/appenders/file.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/file.rb
|
MIT
|
def reopen
@mutex.synchronize {
if defined? @io && @io
flush
@io.close rescue nil
end
@io = open_file
}
super
self
end
|
Reopen the connection to the underlying logging destination. If the
connection is currently closed then it will be opened. If the connection
is currently open then it will be closed and immediately opened.
|
reopen
|
ruby
|
TwP/logging
|
lib/logging/appenders/file.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/file.rb
|
MIT
|
def initialize( name, io, opts = {} )
unless io.respond_to? :write
raise TypeError, "expecting an IO object but got '#{io.class.name}'"
end
@io = io
@io.sync = true if io.respond_to? :sync=
@close_method = :close
super(name, opts)
configure_buffering(opts)
end
|
call-seq:
IO.new( name, io )
IO.new( name, io, :layout => layout )
Creates a new IO Appender using the given name that will use the _io_
stream as the logging destination.
|
initialize
|
ruby
|
TwP/logging
|
lib/logging/appenders/io.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/io.rb
|
MIT
|
def close( *args )
return self if @io.nil?
super
io, @io = @io, nil
if ![STDIN, STDERR, STDOUT].include?(io)
io.send(@close_method) if @close_method && io.respond_to?(@close_method)
end
rescue IOError
ensure
return self
end
|
call-seq:
close( footer = true )
Close the appender and writes the layout footer to the logging
destination if the _footer_ flag is set to +true+. Log events will
no longer be written to the logging destination after the appender
is closed.
|
close
|
ruby
|
TwP/logging
|
lib/logging/appenders/io.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/io.rb
|
MIT
|
def reopen
super
@io.sync = true if @io.respond_to? :sync=
self
end
|
Reopen the connection to the underlying logging destination. If the
connection is currently closed then it will be opened. If the connection
is currently open then it will be closed and immediately opened. If
supported, the IO will have its sync mode set to `true` so that all writes
are immediately flushed to the underlying operating system.
|
reopen
|
ruby
|
TwP/logging
|
lib/logging/appenders/io.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/io.rb
|
MIT
|
def canonical_write( str )
return self if @io.nil?
str = str.force_encoding(encoding) if encoding && str.encoding != encoding
@mutex.synchronize { @io.write str }
self
rescue StandardError => err
handle_internal_error(err)
end
|
This method is called by the buffering code when messages need to be
written to the logging destination.
|
canonical_write
|
ruby
|
TwP/logging
|
lib/logging/appenders/io.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/io.rb
|
MIT
|
def initialize( name, opts = {} )
@roller = Roller.new(
opts.fetch(:filename, name),
age: opts.fetch(:age, nil),
size: opts.fetch(:size, nil),
roll_by: opts.fetch(:roll_by, nil),
keep: opts.fetch(:keep, nil)
)
# grab our options
@size = opts.fetch(:size, nil)
@size = Integer(@size) unless @size.nil?
@age_fn = self.filename + '.age'
@age_fn_mtime = nil
@age = opts.fetch(:age, nil)
# create our `sufficiently_aged?` method
build_singleton_methods
FileUtils.touch(@age_fn) if @age && !::File.file?(@age_fn)
# we are opening the file in read/write mode so that a shared lock can
# be used on the file descriptor => http://pubs.opengroup.org/onlinepubs/009695399/functions/fcntl.html
self.encoding = opts.fetch(:encoding, self.encoding)
io = open_file
super(name, io, opts)
# if the truncate flag was set to true, then roll
roll_now = opts.fetch(:truncate, false)
if roll_now
copy_truncate
@roller.roll_files
end
end
|
call-seq:
RollingFile.new( name, opts )
Creates a new Rolling File Appender. The _name_ is the unique Appender
name used to retrieve this appender from the Appender hash. The only
required option is the filename to use for creating log files.
[:filename] The base filename to use when constructing new log
filenames.
The "rolling" portion of the filename can be configured via some simple
pattern templates. For numbered rolling, you can use {{.%d}}
"logname{{.%d}}.log" => ["logname.log", "logname.1.log", "logname.2.log" ...]
"logname.log{{-%d}}" => ["logname.log", "logname.log-1", "logname.log-2" ...]
And for date rolling you can use `strftime` patterns:
"logname{{.%Y%m%d}}.log" => ["logname.log, "logname.20130626.log" ...]
"logname{{.%Y-%m-%dT%H:%M:%S}}.log" => ["logname.log, "logname.2013-06-26T22:03:31.log" ...]
If the defaults suit you fine, just pass in the :roll_by option and use
your normal log filename without any pattern template.
The following options are optional:
[:layout] The Layout that will be used by this appender. The Basic
layout will be used if none is given.
[:truncate] When set to true any existing log files will be rolled
immediately and a new, empty log file will be created.
[:size] The maximum allowed size (in bytes) of a log file before
it is rolled.
[:age] The maximum age (in seconds) of a log file before it is
rolled. The age can also be given as 'daily', 'weekly',
or 'monthly'.
[:keep] The number of rolled log files to keep.
[:roll_by] How to name the rolled log files. This can be 'number' or
'date'.
|
initialize
|
ruby
|
TwP/logging
|
lib/logging/appenders/rolling_file.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/rolling_file.rb
|
MIT
|
def reopen
@mutex.synchronize {
if defined? @io && @io
flush
@io.close rescue nil
end
@io = open_file
}
super
self
end
|
Reopen the connection to the underlying logging destination. If the
connection is currently closed then it will be opened. If the connection
is currently open then it will be closed and immediately opened.
|
reopen
|
ruby
|
TwP/logging
|
lib/logging/appenders/rolling_file.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/rolling_file.rb
|
MIT
|
def copy_file_mtime
return nil unless ::File.exist?(copy_file)
::File.mtime(copy_file)
rescue Errno::ENOENT
nil
end
|
Returns the modification time of the copy file if one exists. Otherwise
returns `nil`.
|
copy_file_mtime
|
ruby
|
TwP/logging
|
lib/logging/appenders/rolling_file.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/rolling_file.rb
|
MIT
|
def canonical_write( str )
return self if @io.nil?
str = str.force_encoding(encoding) if encoding && str.encoding != encoding
@mutex.synchronize {
@io.flock_sh { @io.write str }
}
if roll_required?
@mutex.synchronize {
@io.flock? {
@age_fn_mtime = nil
copy_truncate if roll_required?
}
@roller.roll_files
}
end
self
rescue StandardError => err
self.level = :off
::Logging.log_internal {"appender #{name.inspect} has been disabled"}
::Logging.log_internal_error(err)
end
|
Write the given _event_ to the log file. The log file will be rolled
if the maximum file size is exceeded or if the file is older than the
maximum age.
|
canonical_write
|
ruby
|
TwP/logging
|
lib/logging/appenders/rolling_file.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/rolling_file.rb
|
MIT
|
def roll_required?
mtime = copy_file_mtime
return false if mtime && (Time.now - mtime) < 180
# check if max size has been exceeded
s = @size ? ::File.size(filename) > @size : false
# check if max age has been exceeded
a = sufficiently_aged?
return (s || a)
end
|
Returns +true+ if the log file needs to be rolled.
|
roll_required?
|
ruby
|
TwP/logging
|
lib/logging/appenders/rolling_file.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/rolling_file.rb
|
MIT
|
def copy_truncate
return unless ::File.exist?(filename)
FileUtils.concat filename, copy_file
@io.truncate(0)
# touch the age file if needed
if @age
FileUtils.touch @age_fn
@age_fn_mtime = nil
end
@roller.roll = true
end
|
Copy the contents of the logfile to another file. Truncate the logfile
to zero length. This method will set the roll flag so that all the
current logfiles will be rolled along with the copied file.
|
copy_truncate
|
ruby
|
TwP/logging
|
lib/logging/appenders/rolling_file.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/rolling_file.rb
|
MIT
|
def age_fn_mtime
@age_fn_mtime ||= ::File.mtime(@age_fn)
end
|
Returns the modification time of the age file.
|
age_fn_mtime
|
ruby
|
TwP/logging
|
lib/logging/appenders/rolling_file.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/rolling_file.rb
|
MIT
|
def build_singleton_methods
method =
case @age
when 'daily'
-> {
now = Time.now
(now.day != age_fn_mtime.day) || (now - age_fn_mtime) > 86400
}
when 'weekly'
-> { (Time.now - age_fn_mtime) > 604800 }
when 'monthly'
-> {
now = Time.now
(now.month != age_fn_mtime.month) || (now - age_fn_mtime) > 2678400
}
when Integer, String
@age = Integer(@age)
-> { (Time.now - age_fn_mtime) > @age }
else
-> { false }
end
self.define_singleton_method(:sufficiently_aged?, method)
end
|
We use meta-programming here to define the `sufficiently_aged?` method for
the rolling appender. The `sufficiently_aged?` method is responsible for
determining if the current log file is older than the rolling criteria -
daily, weekly, etc.
Returns this rolling file appender instance
|
build_singleton_methods
|
ruby
|
TwP/logging
|
lib/logging/appenders/rolling_file.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/rolling_file.rb
|
MIT
|
def initialize( filename, age: nil, size: nil, roll_by: nil, keep: nil )
# raise an error if a filename was not given
@fn = filename
raise ArgumentError, 'no filename was given' if @fn.nil?
if (m = RGXP.match @fn)
@roll_by = ("#{m[2]}%d" == m[1]) ? :number : :date
else
@roll_by =
case roll_by
when 'number'; :number
when 'date'; :date
else
(age && !size) ? :date : :number
end
ext = ::File.extname(@fn)
bn = ::File.join(::File.dirname(@fn), ::File.basename(@fn, ext))
@fn = if :date == @roll_by && %w[daily weekly monthly].include?(age)
"#{bn}{{.%Y%m%d}}#{ext}"
elsif :date == @roll_by
"#{bn}{{.%Y%m%d-%H%M%S}}#{ext}"
else
"#{bn}{{.%d}}#{ext}"
end
end
@fn = ::File.expand_path(@fn)
::Logging::Appenders::File.assert_valid_logfile(filename)
@roll = false
@keep = keep.nil? ? nil : Integer(keep)
end
|
Create a new roller. See the RollingFile#initialize documentation for
the list of options.
filename - the name of the file to roll
age - the age of the file at which it should be rolled
size - the size of the file in bytes at which it should be rolled
roll_by - roll either by 'number' or 'date'
keep - the number of log files to keep when rolling
|
initialize
|
ruby
|
TwP/logging
|
lib/logging/appenders/rolling_file.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/rolling_file.rb
|
MIT
|
def filename
return @filename if defined? @filename
@filename = (@fn =~ RGXP ? @fn.sub(RGXP, '') : @fn.dup)
@filename.freeze
end
|
Returns the regular log file name without any roller text.
|
filename
|
ruby
|
TwP/logging
|
lib/logging/appenders/rolling_file.rb
|
https://github.com/TwP/logging/blob/master/lib/logging/appenders/rolling_file.rb
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.