Created
August 23, 2013 21:36
-
-
Save venkatd/6324284 to your computer and use it in GitHub Desktop.
A wrapper around tracing that is easier to use and lets you filter what you want.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Tracer | |
Trace = Struct.new(:event, :file, :line, :id, :binding, :klass) | |
def initialize(filename, params = {}) | |
@filename = filename | |
@enabled = false | |
@classes = params.fetch(:classes) { [/.*/] } | |
@files = params.fetch(:files) { [/.*/] } | |
@classes = Array(@classes) | |
@files = Array(@files) | |
open_trace_file | |
set_handler | |
end | |
def enabled? | |
@enabled | |
end | |
def enable | |
@enabled = true | |
end | |
def disable | |
@enabled = false | |
end | |
private | |
attr_reader :filename, :trace_file, :classes, :files | |
def on_trace(trace) | |
if enabled? && is_class_method?(trace) && matches?(trace) | |
log trace | |
end | |
end | |
def set_handler | |
set_trace_func proc { |event, file, line, id, binding, klass| | |
on_trace Trace.new(event, file, line, id, binding, klass) | |
} | |
end | |
def log(trace) | |
trace_file.puts "#{trace.file}:#{trace.line} #{trace.klass}##{trace.id}" | |
end | |
def is_class_method?(trace) | |
trace.event == 'call' && trace.klass.is_a?(::Class) | |
end | |
def matches?(trace) | |
classes.any? { |pattern| pattern === trace.klass.to_s } | |
end | |
def open_trace_file | |
@trace_file = open(filename, 'w') | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
tracer = Tracer.new 'trace.txt', classes: /active|postgis/i | |
tracer.enable | |
# write some code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment