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

Parameters:

  • task_full_name (String)


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

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)

Parameters:

  • msg (String)
  • object (Object) (defaults to: nil)


71
72
73
74
75
# File 'lib/logged_task.rb', line 71

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)

Parameters:

  • msg (String)
  • object (Object) (defaults to: nil)


57
58
59
# File 'lib/logged_task.rb', line 57

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

- (Object) summary



77
78
79
80
81
82
83
84
85
86
# File 'lib/logged_task.rb', line 77

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

- (String) time_str (private)

Returns:

  • (String)


91
92
93
# File 'lib/logged_task.rb', line 91

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

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

Parameters:

  • msg (String)
  • object (Object) (defaults to: nil)


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

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)

Parameters:

  • msg (String)
  • object (Object)
  • color (Term::ANSIColor) (defaults to: nil)


98
99
100
101
102
103
104
105
# File 'lib/logged_task.rb', line 98

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)

Parameters:

  • fd (File)
  • msg (String)
  • object (Object)
  • plain (Boolean)


111
112
113
114
# File 'lib/logged_task.rb', line 111

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