快速把Apache訪問日誌即時寫入mysql資料庫

來源:互聯網
上載者:User

在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之類相對不重要的資訊。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.