Skip to content

Commit

Permalink
Merge pull request crystal-lang#335 from bcardiff/logger
Browse files Browse the repository at this point in the history
Use Crystal 0.34 Log module (if possible)
  • Loading branch information
Brian J. Cardiff authored Mar 25, 2020
2 parents e4f398f + e1b1090 commit b0ac422
Show file tree
Hide file tree
Showing 17 changed files with 134 additions and 64 deletions.
2 changes: 1 addition & 1 deletion spec/unit/spec_helper.cr
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ require "../../src/resolvers/*"
require "../support/factories"

module Shards
logger.level = Logger::Severity::WARN
set_warning_log_level

class Dependency
def self.from_name_config(name, config) : self
Expand Down
8 changes: 4 additions & 4 deletions src/cli.cr
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ module Shards
opts.on("--version", "Print the `shards` version.") { puts self.version_string; exit }
opts.on("--production", "Run in release mode. No development dependencies and strict sync between shard.yml and shard.lock.") { self.production = true }
opts.on("--local", "Don't update remote repositories, use the local cache only.") { self.local = true }
opts.on("-v", "--verbose", "Increase the log verbosity, printing all debug statements.") { self.logger.level = Logger::Severity::DEBUG }
opts.on("-q", "--quiet", "Decrease the log verbosity, printing only warnings and errors.") { self.logger.level = Logger::Severity::WARN }
opts.on("-v", "--verbose", "Increase the log verbosity, printing all debug statements.") { self.set_debug_log_level }
opts.on("-q", "--quiet", "Decrease the log verbosity, printing only warnings and errors.") { self.set_warning_log_level }
opts.on("-h", "--help", "Print usage synopsis.") { self.display_help_and_exit(opts) }

opts.unknown_args do |args, options|
Expand Down Expand Up @@ -100,12 +100,12 @@ end
begin
Shards.run
rescue ex : OptionParser::InvalidOption
Shards.logger.fatal ex.message
Shards::Log.fatal { ex.message }
exit 1
rescue ex : Shards::ParseError
ex.to_s(STDERR)
exit 1
rescue ex : Shards::Error
Shards.logger.error ex.message
Shards::Log.error { ex.message }
exit 1
end
6 changes: 3 additions & 3 deletions src/commands/build.cr
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ module Shards
class Build < Command
def run(targets, options)
unless Dir.exists?(Shards.bin_path)
Shards.logger.debug "mkdir #{Shards.bin_path}"
Log.debug { "mkdir #{Shards.bin_path}" }
Dir.mkdir(Shards.bin_path)
end

Expand All @@ -23,15 +23,15 @@ module Shards
end

private def build(target, options)
Shards.logger.info { "Building: #{target.name}" }
Log.info { "Building: #{target.name}" }

args = [
"build",
"-o", File.join(Shards.bin_path, target.name),
target.main,
]
options.each { |option| args << option }
Shards.logger.debug { "crystal #{args.join(' ')}" }
Log.debug { "crystal #{args.join(' ')}" }

error = IO::Memory.new
status = Process.run("crystal", args: args, output: Process::Redirect::Inherit, error: error)
Expand Down
12 changes: 6 additions & 6 deletions src/commands/check.cr
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ module Shards
verify(spec.development_dependencies) unless Shards.production?
end

Shards.logger.info "Dependencies are satisfied"
Log.info { "Dependencies are satisfied" }
end

private def has_dependencies?
Expand All @@ -20,11 +20,11 @@ module Shards

private def verify(dependencies)
dependencies.each do |dependency|
Shards.logger.debug { "#{dependency.name}: checking..." }
Log.debug { "#{dependency.name}: checking..." }
resolver = Shards.find_resolver(dependency)

unless _spec = resolver.installed_spec
Shards.logger.debug { "#{dependency.name}: not installed" }
Log.debug { "#{dependency.name}: not installed" }
raise Error.new("Dependencies aren't satisfied. Install them with 'shards install'")
end

Expand All @@ -38,13 +38,13 @@ module Shards

private def installed?(dependency, spec)
unless lock = locks.find { |d| d.name == spec.name }
Shards.logger.debug { "#{dependency.name}: not locked" }
Log.debug { "#{dependency.name}: not locked" }
return false
end

if version = lock["version"]?
if Versions.resolve([version], dependency.version).empty?
Shards.logger.debug { "#{dependency.name}: lock conflict" }
Log.debug { "#{dependency.name}: lock conflict" }
return false
else
return spec.version == version
Expand All @@ -60,7 +60,7 @@ module Shards
# end

if Versions.resolve([spec.version], dependency.version).empty?
Shards.logger.debug { "#{dependency.name}: version mismatch" }
Log.debug { "#{dependency.name}: version mismatch" }
return false
end

Expand Down
4 changes: 2 additions & 2 deletions src/commands/command.cr
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,14 @@ module Shards
end

def write_lockfile(packages)
Shards.logger.info { "Writing #{LOCK_FILENAME}" }
Log.info { "Writing #{LOCK_FILENAME}" }
Shards::Lock.write(packages, LOCK_FILENAME)
end

def handle_resolver_errors
yield
rescue e : Molinillo::ResolverError
Shards.logger.error e.message
Log.error { e.message }
raise Shards::Error.new("Failed to resolve dependencies")
end
end
Expand Down
2 changes: 1 addition & 1 deletion src/commands/init.cr
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ module Shards
ECR.embed "#{__DIR__}/../templates/shard.yml.ecr", "__str__"
end)

Shards.logger.info "Created #{SPEC_FILENAME}"
Log.info { "Created #{SPEC_FILENAME}" }
end

private def name
Expand Down
6 changes: 3 additions & 3 deletions src/commands/install.cr
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ module Shards
module Commands
class Install < Command
def run
Shards.logger.info { "Resolving dependencies" }
Log.info { "Resolving dependencies" }

solver = MolinilloSolver.new(spec)

Expand Down Expand Up @@ -72,11 +72,11 @@ module Shards

private def install(package : Package)
if package.installed?
Shards.logger.info { "Using #{package.name} (#{package.report_version})" }
Log.info { "Using #{package.name} (#{package.report_version})" }
return
end

Shards.logger.info { "Installing #{package.name} (#{package.report_version})" }
Log.info { "Installing #{package.name} (#{package.report_version})" }
package.install
package
end
Expand Down
2 changes: 1 addition & 1 deletion src/commands/list.cr
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ module Shards

# FIXME: duplicated from Check#verify
unless _spec = resolver.installed_spec
Shards.logger.debug { "#{dependency.name}: not installed" }
Log.debug { "#{dependency.name}: not installed" }
raise Error.new("Dependencies aren't satisfied. Install them with 'shards install'")
end

Expand Down
2 changes: 1 addition & 1 deletion src/commands/lock.cr
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ module Shards
module Commands
class Lock < Command
def run(shards : Array(String), print = false, update = false)
Shards.logger.info { "Resolving dependencies" }
Log.info { "Resolving dependencies" }

solver = MolinilloSolver.new(spec)

Expand Down
8 changes: 4 additions & 4 deletions src/commands/outdated.cr
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ module Shards
def run(@prereleases = false)
return unless has_dependencies?

Shards.logger.info { "Resolving dependencies" }
Log.info { "Resolving dependencies" }

solver = MolinilloSolver.new(spec, @prereleases)
solver.prepare(development: !Shards.production?)
Expand All @@ -20,10 +20,10 @@ module Shards
packages.each { |package| analyze(package) }

if @up_to_date
Shards.logger.info "Dependencies are up to date!"
Log.info { "Dependencies are up to date!" }
else
@output.rewind
Shards.logger.warn "Outdated dependencies:"
Log.warn { "Outdated dependencies:" }
puts @output.to_s
end
end
Expand All @@ -33,7 +33,7 @@ module Shards
installed = resolver.installed_spec.try(&.version)

unless installed
Shards.logger.warn { "#{package.name}: not installed" }
Log.warn { "#{package.name}: not installed" }
return
end

Expand Down
6 changes: 3 additions & 3 deletions src/commands/prune.cr
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,16 @@ module Shards
name = File.basename(path)

if locks.none? { |d| d.name == name }
Shards.logger.debug "rm -rf '#{Helpers::Path.escape(path)}'"
Log.debug { "rm -rf '#{Helpers::Path.escape(path)}'" }
FileUtils.rm_rf(path)

sha1 = "#{path}.sha1"
if File.exists?(sha1)
Shards.logger.debug "rm '#{Helpers::Path.escape(sha1)}'"
Log.debug { "rm '#{Helpers::Path.escape(sha1)}'" }
File.delete(sha1)
end

Shards.logger.info "Pruned #{File.join(File.basename(Shards.install_path), name)}"
Log.info { "Pruned #{File.join(File.basename(Shards.install_path), name)}" }
end
end
end
Expand Down
6 changes: 3 additions & 3 deletions src/commands/update.cr
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ module Shards
module Commands
class Update < Command
def run(shards : Array(String))
Shards.logger.info { "Resolving dependencies" }
Log.info { "Resolving dependencies" }

solver = MolinilloSolver.new(spec)

Expand Down Expand Up @@ -40,11 +40,11 @@ module Shards

private def install(package : Package)
if package.installed?
Shards.logger.info { "Using #{package.name} (#{package.report_version})" }
Log.info { "Using #{package.name} (#{package.report_version})" }
return
end

Shards.logger.info { "Installing #{package.name} (#{package.report_version})" }
Log.info { "Installing #{package.name} (#{package.report_version})" }
package.install
package
end
Expand Down
2 changes: 1 addition & 1 deletion src/config.cr
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ module Shards
end

if File.exists?(legacy_install_path)
Shards.logger.warn "Shards now installs dependencies into the 'lib' folder. You may delete the legacy 'libs' folder."
Log.warn { "Shards now installs dependencies into the 'lib' folder. You may delete the legacy 'libs' folder." }
end
end

Expand Down
116 changes: 93 additions & 23 deletions src/logger.cr
Original file line number Diff line number Diff line change
@@ -1,42 +1,112 @@
require "logger"
require "colorize"

module Shards
LOGGER_COLORS = {
"ERROR" => :red,
"WARN" => :light_yellow,
"INFO" => :light_green,
"DEBUG" => :light_gray,
}

@@colors = true

def self.colors=(value)
@@colors = value
end
end

{% if compare_versions(Crystal::VERSION, "0.34.0-0") > 0 %}
require "log"

Log.setup_from_env(
level: ENV.fetch("CRYSTAL_LOG_LEVEL", "INFO"),
sources: ENV.fetch("CRYSTAL_LOG_SOURCES", "shards.*"),
backend: Log::IOBackend.new.tap do |backend|
backend.formatter = Shards::FORMATTER
end
)

module Shards
Log = ::Log.for(self)

def self.set_warning_log_level
Log.level = ::Log::Severity::Warning
end

@@logger : Logger?
def self.set_debug_log_level
Log.level = ::Log::Severity::Debug
end

LOGGER_COLORS = {
::Log::Severity::Error => :red,
::Log::Severity::Warning => :light_yellow,
::Log::Severity::Info => :light_green,
::Log::Severity::Debug => :light_gray,
}

def self.logger
@@logger ||= Logger.new(STDOUT).tap do |logger|
logger.progname = "shards"
logger.level = Logger::Severity::INFO
FORMATTER = ::Log::Formatter.new do |entry, io|
message = entry.message

logger.formatter = Logger::Formatter.new do |severity, _datetime, _progname, message, io|
if @@colors
io << if color = LOGGER_COLORS[severity.to_s]?
if idx = message.index(' ')
message[0...idx].colorize(color).to_s + message[idx..-1]
if @@colors
io << if color = LOGGER_COLORS[entry.severity]?
if idx = message.index(' ')
message[0...idx].colorize(color).to_s + message[idx..-1]
else
message.colorize(color)
end
else
message
end
else
io << entry.severity.label[0] << ": " << message
end
end
end
{% else %}
require "logger"

module Shards
LOGGER_COLORS = {
"ERROR" => :red,
"WARN" => :light_yellow,
"INFO" => :light_green,
"DEBUG" => :light_gray,
}

@@logger : Logger?

def self.logger
@@logger ||= Logger.new(STDOUT).tap do |logger|
logger.progname = "shards"
logger.level = Logger::Severity::INFO

logger.formatter = Logger::Formatter.new do |severity, _datetime, _progname, message, io|
if @@colors
io << if color = LOGGER_COLORS[severity.to_s]?
if idx = message.index(' ')
message[0...idx].colorize(color).to_s + message[idx..-1]
else
message.colorize(color)
end
else
message.colorize(color)
message
end
else
message
io << severity.to_s[0] << ": " << message
end
else
io << severity.to_s[0] << ": " << message
end
end
end

def self.set_warning_log_level
logger.level = Logger::Severity::WARN
end

def self.set_debug_log_level
logger.level = Logger::Severity::DEBUG
end

module Log
{% for severity in %w(debug info warn error fatal) %}
def self.{{severity.id}}
Shards.logger.{{severity.id}} do
yield
end
end
{% end %}
end
end
end
{% end %}
Loading

0 comments on commit b0ac422

Please sign in to comment.