在apache設定檔或是虛擬機器主機設定檔中(也就是配置LogFormat以及CustomLog部分)增加如下內容:
LogFormat “INSERT INTO apachelog (ID, dateTime, IP, URL, code, referer, userAgent, size, request) VALUES ( NULL , \”%{%Y-%m-%d %H:%M:%S}t\”, \”%a\”, \”%U\”, \”%>s\”, \” %{Referer}i\”, \”%{User-Agent}i\”, %b, %T);” sqlcomm
CustomLog “| /usr/bin/mysql –user=root –password=” –database=apachealog” sqlcomm
在Mysql資料庫中建立資料庫及資料表:
mysql> create database apachealog;
mysql> show create table apachealog;
CREATE TABLE `apachelog` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`dateTime` datetime NOT NULL,
`IP` varchar(15) NOT NULL,
`URL` varchar(256) NOT NULL,
`code` varchar(3) NOT NULL,
`referer` varchar(256) NOT NULL,
`userAgent` varchar(256) NOT NULL,
`size` int(11) NOT NULL,
`request` float NOT NULL,
PRIMARY KEY (`ID`),
KEY `dateTime` (`dateTime`)
) ENGINE=MyISAM AUTO_INCREMENT=40 DEFAULT CHARSET=latin1;
實現思路:
先是利用 LogFormat設定將日誌轉換為接近sql的格式,再通過CustomLog 調用pipe實現mysql寫入。
註:Apache的日誌格式可以參照官方文檔:http://httpd.apache.org/docs/2.2/mod /mod_log_config.html#formats,也可以使用SetEnvIf配合Regex過濾掉諸如圖片、CSS、JS之類相對不重要的資訊。