Tuesday, June 7, 2011

Still dealing with the old problem of Logging

Well it is two issues:
  1. Finding the basename of the program or module your code is within.
  2. Setting up the logger given the answer to the previous issue.
NOTE: I am playing with some CSS to display code. I am using the simplest which is applying a class to a div.


Getting the Fully Qualified Directory Name (FQDN) of the project directory; assuming the program is in a project/{bin,sbin,script} directory.
require 'pathname'
BASE_DIR = Pathname(__FILE__).dirname.expand_path(Dir.pwd).parent
puts "BASE_DIR=" + BASE_DIR.to_s
LIB_DIR = BASE_DIR + 'lib'
puts "LIB_DIR=" + LIB_DIR.to_s
$:.unshift LIB_DIR.to_s

Set up the logger format. This doesn't grab the library name or line number.
log = Logger.new(STDOUT)
log.level = Logger::DEBUG
log.progname = File.basename(__FILE__)
log.datetime_format = "%Y-%m-%d %H:%M:%S"
log.formatter = proc { |sev, dt, prog, msg|
"[#{dt.strftime("%Y-%m-%d %H:%M:%S")}] #{prog}(#{Process.pid}) #{"%-5s"%sev}: #{msg}\n"
}
I am thinking of adding more data into each line. Like PID, line number, class/module name, and function. It is alot but if you are using the logs for debugging more the merrier and while I prefer maintaining the sanctity of 80 columns for code. Ultra wide log lines is not sacrilege.

Also, there are two more questions to be answered: do I repeat this code in every file? how do I abstract it into a library?

No comments:

Post a Comment