Skip to content

Commit

Permalink
Merge pull request #3 from Sija/develop
Browse files Browse the repository at this point in the history
v2.0
  • Loading branch information
Sija authored Jul 13, 2020
2 parents ecfb8fe + f913f0c commit 415f590
Show file tree
Hide file tree
Showing 10 changed files with 203 additions and 115 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ crystal:
- latest
- nightly

matrix:
jobs:
allow_failures:
- crystal: nightly

Expand Down
6 changes: 3 additions & 3 deletions shard.yml
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
name: debug
version: 1.1.0
version: 2.0.0

authors:
- Sijawusz Pur Rahnama <[email protected]>

development_dependencies:
ameba:
github: crystal-ameba/ameba
version: ~> 0.10.0
version: ~> 0.13.0

crystal: 0.30.1
crystal: 0.35.0

license: MIT
71 changes: 71 additions & 0 deletions spec/debug_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,78 @@ enum Baz
Three
end

ENV_DEBUG_KEY = "DEBUG"

describe Debug do
describe ".enabled?" do
it "should be true when ENV debug key is set to '1'" do
previous_env = ENV[ENV_DEBUG_KEY]?
begin
ENV[ENV_DEBUG_KEY] = "1"
Debug.enabled?.should be_true
ensure
ENV[ENV_DEBUG_KEY] = previous_env
end
end

it "should be false when ENV debug key is set to value other than '1'" do
previous_env = ENV[ENV_DEBUG_KEY]?
begin
ENV[ENV_DEBUG_KEY] = "10"
Debug.enabled?.should be_false
ensure
ENV[ENV_DEBUG_KEY] = previous_env
end
end

it "should be false when ENV debug key is unset" do
previous_env = ENV.delete(ENV_DEBUG_KEY)
begin
Debug.enabled?.should be_false
ensure
ENV[ENV_DEBUG_KEY] = previous_env
end
end

it "setting explicit (non-nil) value should have priority over ENV" do
previous_env = ENV.delete(ENV_DEBUG_KEY)
begin
Debug.enabled = true
Debug.enabled?.should be_true
ensure
ENV[ENV_DEBUG_KEY] = previous_env
Debug.enabled = nil
end
end
end

it "passes :severity as Log::Entry#severity" do
next unless Debug.enabled?

::Log.capture do |logs|
debug!("foo")
debug!("bar", severity: :trace)

logs.check :debug, /foo/
logs.next :trace, /bar/
end
end

it "passes :progname into Log::Entry#data" do
next unless Debug.enabled?

progname = "bar.cr"

::Log.capture do |logs|
debug!("foo", progname: progname)

logs.check :debug, /foo/

entry = logs.entry?.should_not be_nil
entry.data[:progname]?.should eq(progname)
end
end

context "with literals" do
it "works with Nil" do
assert_debug nil
Expand Down
46 changes: 22 additions & 24 deletions spec/spec_helper.cr
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require "spec"
require "log/spec"
require "../src/debug"

Debug.configure do |settings|
Expand All @@ -9,31 +10,28 @@ end
macro assert_debug(exp, *, file = __FILE__, line = __LINE__)
%ret = nil

%previous_logger = Debug.logger
begin
IO::Memory.new.tap do |io|
Debug.logger = Debug::Logger.new(io)
Debug.logger.tap do |logger|
%ret = debug!(value = {{ exp }})

case value
when Value then %ret.should eq(value)
when Reference then %ret.should be(value)
end
%ret.should be_a(typeof(value))

if Debug::ACTIVE && Debug.enabled?
relative_filename = {{ file }}.lchop(Dir.current + "/")

io.to_s.should contain "#{relative_filename}:{{ line }}"
io.to_s.should contain {{ exp.stringify }}
else
io.to_s.should be_empty
end
end
::Log.capture do |%logs|
%ret, %value =
debug!(__value__ = {{ exp }}),
__value__

case %value
when Value then %ret.should eq %value
when Reference then %ret.should be %value
end

%ret.should be_a typeof(%value)

if ::Debug::ACTIVE && ::Debug.enabled?
%relative_path = Path[{{ file }}].relative_to(Dir.current).to_s

%entry = %logs.check("whatever", &.nil?.!).entry?.should_not be_nil # here be dragons
%entry.severity.should eq ::Log::Severity::Debug
%entry.message.should contain "#{%relative_path}:{{ line }}"
%entry.message.should contain {{ exp.stringify }}
else
%logs.empty
end
ensure
Debug.logger = %previous_logger
end

%ret
Expand Down
98 changes: 50 additions & 48 deletions src/debug.cr
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require "logger"
require "log"
require "colorize"

module Debug
Expand All @@ -18,7 +18,7 @@ module Debug
end

macro log(*args,
severity = Logger::Severity::DEBUG,
severity = :debug,
progname = nil,
backtrace_offset = 0,
file = __FILE__,
Expand All @@ -43,67 +43,69 @@ module Debug
%colors = %settings.colors

{% for arg, i in args %}
%exp, %val =
%arg_expressions[{{ i }}], %arg_values[{{ i }}]

%str = String.build do |%str|
case %settings.location_detection
when .compile?
%relative_filepath = {{ file }}.lchop(Dir.current + "/")
if %relative_filepath
if %max_path_length = %settings.max_path_length
if %relative_filepath.size > %max_path_length
%relative_filepath = "" + %relative_filepath[-%max_path_length..]
::Debug.logger.{{ severity.id }} do |%emitter|
%exp, %val =
%arg_expressions[{{ i }}], %arg_values[{{ i }}]

%ret = String.build do |%str|
case %settings.location_detection
when .compile?
%relative_path = Path[{{ file }}].relative_to(Dir.current).to_s
if %relative_path
if %max_path_length = %settings.max_path_length
if %relative_path.size > %max_path_length
%relative_path = "" + %relative_path[-%max_path_length..]
end
end
%str << "#{%relative_path}:{{ line }}"
.colorize(%colors[:path])
end
%str << "#{%relative_filepath}:{{ line }}"
.colorize(%colors[:path])
end

%def_name = {{ @def && @def.name.stringify }}
if %def_name
%str << " (#{%def_name})"
.colorize(%colors[:method])
end
%str << " -- "
%def_name = {{ @def && @def.name.stringify }}
if %def_name
%str << " (#{%def_name})"
.colorize(%colors[:method])
end
%str << " -- "

when .runtime?
%DEBUG_CALLER_PATTERN = /caller:Array\(String\)/i
%caller_list = caller
when .runtime?
%DEBUG_CALLER_PATTERN = /caller:Array\(String\)/i
%caller_list = caller

if %caller_list.any?(&.match(%DEBUG_CALLER_PATTERN))
while !%caller_list.empty? && %caller_list.first? !~ %DEBUG_CALLER_PATTERN
if %caller_list.any?(&.match(%DEBUG_CALLER_PATTERN))
while !%caller_list.empty? && %caller_list.first? !~ %DEBUG_CALLER_PATTERN
%caller_list.shift?
end
%caller_list.shift?
end
%caller_list.shift?
end

{% if backtrace_offset > 0 %}
%caller_list.shift({{ backtrace_offset }})
{% end %}
{% if backtrace_offset > 0 %}
%caller_list.shift({{ backtrace_offset }})
{% end %}

if %caller = %caller_list.first?
%str << %caller
.colorize(%colors[:method])
%str << " -- "
if %caller = %caller_list.first?
%str << %caller
.colorize(%colors[:method])
%str << " -- "
end
end
end

%str << '\n' if %exp['\n']?
%str << %exp
.colorize(%colors[:expression])
%str << '\n' if %exp['\n']?
%str << %exp
.colorize(%colors[:expression])

%str << " = "
.colorize(%colors[:decorator])
%str << " = "
.colorize(%colors[:decorator])

%val.to_debug.tap do |%pretty_val|
%str << '\n' if %pretty_val['\n']?
%str << %pretty_val
%val.to_debug.tap do |%pretty_val|
%str << '\n' if %pretty_val['\n']?
%str << %pretty_val
end
%str << " (" << typeof(%val).to_s.colorize(%colors[:type]) << ')'
end
%str << " (" << typeof(%val).to_s.colorize(%colors[:type]) << ')'
end

::Debug.logger.log({{ severity }}, %str, {{ progname }})
%emitter.emit(%ret, progname: {{ progname }})
end
{% end %}
end
{% end %}
Expand Down
44 changes: 22 additions & 22 deletions src/debug/logger.cr
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
module Debug
class Logger < ::Logger
private DEFAULT_FORMATTER = Formatter.new do |severity, datetime, progname, message, io|
parts = [] of String | Colorize::Object(String)
private DEFAULT_FORMATTER = Log::Formatter.new do |entry, io|
parts = [] of String | Colorize::Object(String)

Logger.settings.tap do |settings|
if settings.show_severity?
parts << severity.to_s.rjust(5).colorize(settings.severity_colors[severity])
end
if settings.show_datetime?
parts << "[#{datetime.to_s.colorize(settings.colors[:datetime])}]"
end
if settings.show_progname? && !progname.empty?
parts << "[#{progname.colorize(settings.colors[:progname])}]"
end
unless parts.empty?
io.tap { parts.join(' ', io) } << " -- "
end
io << message
Logger.settings.tap do |settings|
if settings.show_severity? && (severity = entry.severity)
parts << severity.label.to_s.rjust(6).colorize(settings.severity_colors[severity])
end
end

def initialize(@io : IO?, @level = Severity::DEBUG, @formatter = DEFAULT_FORMATTER, @progname = "")
super
if settings.show_datetime? && (timestamp = entry.timestamp)
parts << "[#{timestamp.to_s.colorize(settings.colors[:datetime])}]"
end
progname = entry.data[:progname]?.try(&.as_s?) || settings.progname
if settings.show_progname? && progname.presence
parts << "[#{progname.colorize(settings.colors[:progname])}]"
end
unless parts.empty?
io.tap { parts.join(io, ' ') } << " -- "
end
io << entry.message
end
end

class_property logger : ::Logger { Logger.new(STDOUT) }
class_property logger : Log do
backend = Log::IOBackend.new(STDOUT, formatter: DEFAULT_FORMATTER)

Log.builder.bind("debug.*", :trace, backend)
Log.for("debug")
end
end

require "./logger/*"
27 changes: 15 additions & 12 deletions src/debug/logger/settings.cr
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,35 @@ class Debug::Logger
class Settings
private module LoggerDelegators
delegate :logger, :logger=, to: Debug
delegate :level, :progname, :progname=, to: :logger
delegate :level, to: :logger

def level=(level : ::Logger::Severity)
def level=(level : Log::Severity)
logger.level = level
end
end

extend LoggerDelegators

class_property? show_severity : Bool = true
class_property? show_datetime : Bool = false
class_property? show_progname : Bool = true
class_property? show_severity = true
class_property? show_datetime = false
class_property? show_progname = true

class_property progname : String?

class_getter colors = {
:datetime => :dark_gray,
:progname => :cyan,
} of Symbol => Colorize::Color

class_getter severity_colors = {
:unknown => :dark_gray,
:error => :red,
:warn => :light_red,
:info => :blue,
:debug => :green,
:fatal => :magenta,
} of Logger::Severity => Colorize::Color
:trace => :white,
:debug => :green,
:info => :blue,
:notice => :dark_gray,
:warn => :light_red,
:error => :red,
:fatal => :magenta,
} of Log::Severity => Colorize::Color
end

class_getter settings = Settings
Expand Down
Loading

0 comments on commit 415f590

Please sign in to comment.