Last active
June 1, 2016 14:34
-
-
Save jah2488/5d29ccc3194aa3250fd035d07fe7e750 to your computer and use it in GitHub Desktop.
First attempt at a light weight logging DSL that makes logging/debugging complicated processes easier to read.
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
require 'pry' | |
module Logger | |
def log(title, opts = {}) | |
__blocks[title] = { | |
successful: true, | |
parent: __blocks[:current], | |
cascade: opts.fetch(:cascade, false) | |
} | |
__blocks[:current] = title | |
out("#{title} STARTED") | |
inc_indent | |
yield | |
dec_indent | |
out("#{title} #{(__blocks[title][:successful]) ? "COMPLETED" : "FAILED"}") | |
end | |
def out(text) | |
puts indent + text | |
end | |
def error(text, exception) | |
puts indent + "ERROR: #{text}" | |
inc_indent | |
puts indent + "Exception: #{exception}" | |
dec_indent | |
block = __blocks[__blocks[:current]] | |
block[:successful] = false | |
if block[:cascade] | |
cascade_failure(block) | |
end | |
end | |
protected | |
def __blocks | |
@__blocks ||= {} | |
end | |
private | |
def indent | |
(" " * @indent_level.to_i) | |
end | |
def inc_indent | |
@indent_level = (@indent_level.to_i + 1) | |
end | |
def dec_indent | |
@indent_level = (@indent_level.to_i - 1) | |
end | |
def cascade_failure(block) | |
return if block.nil? | |
block[:successful] = false | |
cascade_failure(__blocks[block[:parent]]) | |
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
require_relative 'fancy_logger_dsl' | |
class OrderLogger | |
include Logger | |
def all | |
log "all" do | |
orders | |
end | |
end | |
def orders | |
# do non-log worthy thing here | |
log "orders" do | |
orders = [] | |
log "Writing to File: /tmp", cascade: true do | |
begin | |
#Write file | |
raise "ERNOECS #{orders}" #some awful error | |
rescue StandardError => e | |
error "Couldn't save file", e | |
end | |
end | |
end | |
end | |
end | |
OrderLogger.new.all |
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
all STARTED | |
orders STARTED | |
Writing to File: /tmp STARTED | |
ERROR: Couldn't save file | |
Exception: ERNOECS [] | |
Writing to File: /tmp FAILED | |
orders FAILED | |
all FAILED |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment