2009-06-05

First YAML log file

I started with an excellent 5 minute tutorial and then added some a simple log file to my code.  Now I have a more or less functional log file writer.  I will improve it as I go on.

# A class for creating logfiles that show what has been done
# designed to be able to fail half way through

class H3Log
  @@default_dir = "C:"
  @@default_prefix = "Logfile"
  @@file_name = ""
  @@indent = 0
  @@indent_text = ""

  def H3Log.timestamp
    return Time.now.strftime('%Y-%m-%dT%H:%M:%S')
  end

  def H3Log.set_default_dir(dir)
    @@default_dir = dir
  end

  def H3Log.set_prefix( prefix)
    @@default_prefix = prefix
  end

  def H3Log.start(msg)
    @@file_name = "#{@@default_dir}\\#{@@default_prefix} #{Time.now.strftime('%Y-%m-%dT%H%M%S')}.yaml" if @@file_name = ""
    @@index_text = ""
    (@@indent*2).times { @@index_text += " "}
    @@indent += 1
    H3Log.msg("--- " + msg)
    H3Log.msg("start: #{H3Log.timestamp}")
  end

  def H3Log.end()
    H3Log.msg("end: #{H3Log.timestamp}")
  end

  def H3Log.msg(msg)
    f=File.open(@@file_name, 'a' )
    f.write("#{@@index_text}#{msg}\n")
    f.close
  end

end

begin
  puts "Start"
  H3Log.set_default_dir('O:\mytestdir)
  H3Log.start("log start")
  H3Log.end
rescue
  puts "had to be rescued"
end

#puts "Waiting for readline #{Time.now} "
#readline

No comments: