Class: LoggedTask::TaskLogger

Inherits:
Object
  • Object
show all
Defined in:
lib/logged_task.rb

Instance Method Summary (collapse)

Constructor Details

- (TaskLogger) initialize(task_full_name)

Returns a new instance of TaskLogger



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/logged_task.rb', line 42

def initialize(task_full_name)
  names = task_full_name.split(":")
  task_name = names.pop
  path = Rails.root.join("log", "rake_tasks")

  FileUtils.mkdir_p(path)
  time = Time.now.strftime('%Y-%m-%d_%H%M%S.%N')
  @log_file = File.new(path.join("#{time}-#{names.join(".")}.#{task_name}.log"), "w")
  @warns_and_errors = []
  @task_full_name = task_full_name
end

Instance Method Details

- (Object) error(msg, object = nil)



64
65
66
67
68
# File 'lib/logged_task.rb', line 64

def error(msg, object=nil)
  msg = "[ERROR]#{time_str}: #{msg}"
  @warns_and_errors << { msg: msg, color: Term::ANSIColor.red }
  write(msg, object, Term::ANSIColor.red)
end

- (Object) info(msg, object = nil)



54
55
56
# File 'lib/logged_task.rb', line 54

def info(msg, object=nil)
  write("[INFO]#{time_str}: #{msg}", object)
end

- (Object) summary



70
71
72
73
74
75
76
77
78
79
# File 'lib/logged_task.rb', line 70

def summary
  # TODO: Write all warnings and errors together
  write("=== Summary of warnings and errors for task #{@task_full_name} ===", nil)
  if @warns_and_errors.empty?
    write("(NONE)", nil)
  else
    @warns_and_errors.each { | e | write(e[:msg], nil, e[:color]) }
  end
  write("", nil)
end

- (Object) time_str (private)



83
84
85
# File 'lib/logged_task.rb', line 83

def time_str
  Time.now.strftime('%Y-%m-%d %H:%M:%S.%3N')
end

- (Object) warn(msg, object = nil)



58
59
60
61
62
# File 'lib/logged_task.rb', line 58

def warn(msg, object=nil)
  msg = "[WARN]#{time_str}: #{msg}"
  @warns_and_errors << { msg: msg, color: Term::ANSIColor.yellow }
  write(msg, object, Term::ANSIColor.yellow)
end

- (Object) write(msg, object, color = nil) (private)



87
88
89
90
91
92
93
94
# File 'lib/logged_task.rb', line 87

def write(msg, object, color=nil)
  write_file(@log_file, msg, object, true)
  @log_file.fsync

  msg = color + msg + Term::ANSIColor.clear unless color.nil?

  write_file($stdout, msg, object, false)
end

- (Object) write_file(fd, msg, object, plain) (private)



96
97
98
99
# File 'lib/logged_task.rb', line 96

def write_file(fd, msg, object, plain)
  fd.puts msg
  fd.puts object.ai(plain: plain) unless object.nil?
end