Home > Perl > Perl and Apache > mod_perl Part 1: Configuring Handlers
mod_perl Part 1: Configuring Handlers
Written by Philip L Yuson   
Who is this for
This article is for those who want to learn how to define mod_perl Handlers in Apache

This is a continuation of last month's topic

What you need to know

You need to know:

  • basics of Apache configuration

  • Perl scripting

Note: mod_perl 1.0 have different handles than mod_perl 2.0. Make sure that you are reading the right documentation. Likewise, some functions in mod_perl 1.0 are not available in mod_perl 2.0

Defining a Handler
A handler has to be defined first before Apache will call it. If there are no handlers defined in the Apache configuration, no handlers will be called.

You define the handlers by specifying them in the configuration file. The Apache server must also be compiled to include the mod_perl module.

A handler can be defined to work on a specific location, directory or file. You include this in the , or directives like so:

<Directory /usr/local/apache/htdocs/modperl/*>
PerlLogHandler Concept::Log

The statement above tells Apache to execute the Concept::Log module if files in the /usr/local/apache/htdocs/modperl directory are accessed. The PerlLogHandler can be used to write logs directly to a MySQL database.

You need to define a Concept::Log module in a Perl library. You can use a startup script to include a library not in the Perl libraries. This is discussed in the previous article

The Concept::Log module can look something like this:

package Concept::Logs;
use strict;
use Apache::Constants;
use Apache::Connection;
use Apache::DBI;
use URI;
use Socket;
sub handler {
my $db = DBI->connect(
'DBI:mysql:database=apachelog', 'root', 'concept');
# Connect to DB
my $r = shift; # Get Request object
my $c = $r->connection; # Get Connection
my $ip= $c->remote_ip; # Get IP Address
my $args = $r->args; # Get Arguments
my $uri = new URI($r->uri); # Get URL
my $path = $uri->path; # Get the Path
my $bytes= $r->bytes_sent; # Get number of bytes
my $sql = qq { insert into log (log_time,
values (current_timestamp,
}; # Build SQL
my $res = $db->do($sql); # Insert

The above handler writes log records onto a MySQL database. This assumes that you have already created a MySQL database and table.

Other Handlers
The mod_perl 2.0 documentation contains a very detailed discussion on the various handlers. You can check it out on Part 5 of their documentation

You can turn on the tracing feature of mod_perl by specifying PerlTrace in the Apache Configuration file. You need to include the trace module in Apache to make this work.

Copyright: © 2018 Philip Yuson