Logging in Perl

Here’s the translation of the Go logging example to Perl, presented in Markdown format suitable for Hugo:

Our example demonstrates various logging techniques in Perl. We’ll use the built-in warn function for basic logging and the Log::Log4perl module for more advanced logging capabilities.

use strict;
use warnings;
use Log::Log4perl qw(:easy);
use JSON;

# Basic logging using warn
warn "standard logger\n";

# Log::Log4perl initialization
Log::Log4perl->easy_init($DEBUG);

# Get the root logger
my $logger = get_logger();

# Logging with timestamp
$logger->info("with timestamp");

# Logging with file and line information
$logger->info("with file/line");

# Creating a custom logger
my $mylog = get_logger("MyLogger");
$mylog->info("from mylog");

# Changing logger name
$mylog = get_logger("OhMyLogger");
$mylog->info("from mylog");

# Logging to a string
my $buffer;
Log::Log4perl->easy_init({ level => $DEBUG, file => \$buffer });
my $buflog = get_logger("BufferLogger");
$buflog->info("hello");
print "from buflog: $buffer";

# JSON structured logging
my $json = JSON->new->utf8;
my $json_logger = get_logger("JSONLogger");
$json_logger->add_appender(
    Log::Log4perl::Appender->new(
        "Log::Log4perl::Appender::String",
        name => "StringAppender"
    )
);
$json_logger->info($json->encode({ message => "hi there" }));
$json_logger->info($json->encode({ message => "hello again", key => "val", age => 25 }));

# Print JSON logs
my $json_appender = $json_logger->appender_by_name("StringAppender");
print $json_appender->string();

This Perl script demonstrates various logging techniques:

  1. We start with basic logging using the built-in warn function.

  2. We then use the Log::Log4perl module, which provides more advanced logging capabilities.

  3. We create loggers with different configurations, including timestamp and file/line information.

  4. We demonstrate how to create custom loggers and change their names.

  5. We show how to log to a string buffer.

  6. Finally, we implement JSON structured logging using the JSON module along with Log::Log4perl.

To run this script, you’ll need to install the Log::Log4perl and JSON modules. You can do this using CPAN:

$ cpan Log::Log4perl JSON

Then, save the script to a file (e.g., logging.pl) and run it:

$ perl logging.perl

The output will look similar to this (timestamps and file paths will vary):

standard logger
2023/08/22 10:45:16 INFO> with timestamp
2023/08/22 10:45:16 INFO> with file/line at logging.pl line 16
2023/08/22 10:45:16 INFO - MyLogger> from mylog
2023/08/22 10:45:16 INFO - OhMyLogger> from mylog
from buflog: 2023/08/22 10:45:16 INFO - BufferLogger> hello
{"message":"hi there"}
{"message":"hello again","key":"val","age":25}

This example demonstrates how to implement various logging techniques in Perl, from basic logging to more advanced structured logging with JSON output.