debugging intermediate

How to log debug messages to file in Perl?

Question

How to log debug messages to file in Perl?

Logging Debug Messages to a File in Perl

Logging debug messages to a file in Perl is a common requirement during development and troubleshooting. Perl provides flexible ways to write to files using built-in filehandles. This allows you to record diagnostic or debugging information persistently for later inspection.

At its core, logging involves opening a filehandle for writing (usually appending), writing messages with timestamps or severity levels, then closing the handle when done. Perl’s open function, combined with print to a filehandle, can be used for simple logging. For more sophisticated needs, modules like Log::Log4perl exist, but here we'll keep it simple using core syntax and concepts.

Perl Concepts Involved

  • open: Opens a filehandle for writing/appending.
  • Filehandles: Explicit handles such as *LOG or scalar references.
  • Sigils: $ for scalars, @ for arrays, % for hashes, and barewords or references for filehandles.
  • Context: Printing to filehandles respects the output context.
  • TMTOWTDI ("There's More Than One Way To Do It"): Perl allows many ways to open and write files.

Common Pitfalls

  • Not checking the success of open can lead to silent failures.
  • Buffering: Filehandles may buffer output; using $|=1; or autoflush can improve immediacy.
  • File mode: Using append (>>) prevents overwriting logs.
  • Security: Avoid logging sensitive data.
  • File permissions: Ensure you have permission to write the log file.

Runnable Example: Simple Debug Logger

#!/usr/bin/perl
use strict;
use warnings;
use IO::Handle;  # Core module to enable autoflush

my $logfile = "debug.log";

# Open log file in append mode
open my $log_fh, '>>', $logfile or die "Cannot open '$logfile' for appending: $!";

# Enable autoflush to write immediately
$log_fh->autoflush(1);

sub debug_log {
    my ($message) = @_;
    # Format: [YYYY-MM-DD HH:MM:SS] DEBUG: message
    my $timestamp = localtime();
    print $log_fh "[$timestamp] DEBUG: $message\n";
}

# Example usage
debug_log("Starting script execution");
for my $i (1..3) {
    debug_log("Loop iteration $i");
}
debug_log("Finished script execution");

print "Debug messages logged to '$logfile'.\n";

This script opens debug.log in append mode, so messages accumulate rather than overwrite. The debug_log sub formats messages with a readable timestamp and severity label.

Using autoflush disables buffering on the filehandle, so logs are written immediately, which is helpful during debugging when you want real-time insight.

Extending This Approach

  • Add log levels (INFO, WARN, ERROR) and filter messages based on verbosity.
  • Use a global or object-oriented logger to avoid repeating the filehandle open/close.
  • Handle potential exceptions or disk full errors during logging.
  • Rotate logs manually or integrate with logrotate to limit file size.

In summary, writing debug logs to a file in Perl is straightforward by opening a filehandle and printing timestamped messages. Use append mode, enable autoflush, and perform error checking on open for a robust basic logging solution.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 37ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Debug messages logged to 'debug.log'.
STDERR
(empty)

Was this helpful?

Related Questions