Skip to content

Instantly share code, notes, and snippets.

@dgwynne
Last active July 12, 2016 05:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgwynne/7bc1611ccd3a3ed3ca649dc379362412 to your computer and use it in GitHub Desktop.
Save dgwynne/7bc1611ccd3a3ed3ca649dc379362412 to your computer and use it in GitHub Desktop.
bunyan output for apache
PerlLogHandler EAIT::Log
package EAIT::Log;
use strict;
use warnings;
use mod_perl;
use Apache::Constants;
use Sys::Hostname;
use POSIX qw(strftime);
use Fcntl qw(:flock);
use Time::HiRes qw(gettimeofday);
use JSON::XS;
open(my $fh, ">>", "/var/www/logs/bunyan.log");
my $hostname = hostname;
sub headers($)
{
my $in = shift;
my $out = { };
foreach my $k ( keys %{ $in } ) {
$out->{ lc($k) } = $in->{$k};
}
return ($out);
}
sub handler
{
my $r = shift;
my @tm = gettimeofday;
my $ts = sprintf("%s.%03dZ", strftime("%Y-%m-%dT%H:%M:%S", gmtime($tm[0])), $tm[1]);
my $res = {
'statusCode' => $r->status,
'headers' => headers($r->headers_out),
'bytes' => $r->bytes_sent,
};
my $scheme = ($r->subprocess_env('HTTPS') ? 'https' : 'http');
my $url = $r->uri;
my $args = $r->args;
if (defined($args)) {
$url .= '?' . $args;
}
my $h = headers($r->headers_in);
my $req = {
'scheme' => $scheme,
'method' => $r->method,
'host' => $r->hostname,
'url' => $url,
'headers' => $h,
'remoteAddress' => $r->connection->remote_ip,
};
if (defined($r->user)) {
$req->{'username'} = $r->user;
}
if ($r->protocol =~ m/^HTTP\/(.*)/) {
$req->{'httpVersion'} = $1;
}
my $msg = {
'v' => 0,
'hostname' => $hostname,
'name' => 'httpd',
'pid' => $$,
'level' => 30, # info
'time' => $ts,
'msg' => sprintf("%s %s://%s%s %d", $r->method, $scheme, $r->hostname, $url, $r->status),
'req' => $req,
'res' => $res,
};
if (defined($h->{'x-request-id'})) {
$msg->{'req_id'} = $h->{'x-request-id'};
}
my $developer = $r->notes('xweb-developer');
if (defined($developer)) {
$msg->{'developer'} = $developer;
}
flock($fh, LOCK_EX);
print $fh (encode_json($msg) . "\n");
flock($fh, LOCK_UN);
return Apache::Constants::DECLINED;
}
1;
__END__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment