DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

A Tool To Split Log Files By Hostname

08.14.2006
| 6526 views |
  • submit to reddit
        This script can be used to split a log file by the hostname in the request. It is designed for use with lighttpd virtual hosting, to prepare the log for Webalizer. It should be run with a cron job and CLI PHP.

<?php
// Copyright (C) 2006 Craig Spurrier
// Released under the terms of the MIT/expat license.

$serverip = "127.0.0.1"; //Set to your IP address or default hostname, so requests without hostnames can be sorted 
$log = file_get_contents("/var/log/lighttpd/access.log"); //Log location
$fh = fopen("/var/log/lighttpd/access.log", 'w'); //Clear the log file
fclose($fh);
$lines = explode ("\n", $log);
foreach ($lines as $line){
$parts = explode (" ", $line);
$hostname = strtolower($parts[1]);
if (substr($hostname, 0, 4) == 'www.'){$hostname = substr($hostname, 4);} //Treat www. as the same as the www-less version
if ($hostname == '-'){$hostname = $serverip;} //Set a hostname for request without hostnames
$fh = fopen("/var/log/lighttpd/users/$hostname.access.log", 'a'); //Add the entry to the log for that hostname. Make sure this script can write to this location.
fwrite($fh, "$line\n");
fclose($fh);
}
?>