Sunday, June 7, 2009

Print-and-log revisited

A month ago, I made a post with a simple print-and-log subroutine called plog.

I was recently asked two questions about this piece of code, and I'll answer them briefly now:
  1. "What's up with the curly braces on a separate line after the sub declaration?"
  2. "Why don't you use DateTime?"
Okay, those should be easy to answer while retaining the illusion of clue:
  1. That's merely a personal preference, it quickly aids me in noticing whether something is a subroutine or a control statement block. I am aware that many Perl programmers disagree, and prefer all blocks to start in the same way regardless of what kind of block it is.
  2. DateTime is an external module which, believe it or not, is not installed on all systems. Some people would also argue that it's bloated and slow. But in case you want to use DateTime instead, and/or check whether it's available run-time, then ... well, see below.
sub plog
{
my $msg = shift;
my $level = shift;
my $dt;
eval {
require DateTime;
$dt = DateTime->now(time_zone=>'local')->strftime("%F %T");
};
if ($@) {
my @lt = localtime;
# Format current datetime manually:
$dt = sprintf("%d-%02d-%02d %02d:%02d:%02d",
$lt[5]+1900,$lt[4]+1,
$lt[3],$lt[2],$lt[1],$lt[0]);
}

(...)
As you can see, there isn't much code saved by using DateTime, even if we know it's already installed and don't need to add paranoia. The method of extracting data from localtime() is well-known, proven, and fairly nice on resources. Use DateTime if you want to, but perhaps it's best to save it for when you need to do more complicated stuff.

2 comments:

Anonymous said...

If the only place you ever deal with dates is in plog, then yes, DateTime is overkill. But that use of localtime is nasty as hell, and if I saw that idiom scattered throughout a codebase I'd be pretty sad.

bakkushan said...

I've posted a new blog entry in response. :)