#!/usr/bin/php
<?php
$cnt = 0;
function getData() {
require "setEnv.php";
//MySQL Connect
$con = mysql_connect("$hostMySQL","$usernameMySQL","$passwordMySQL");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("$databaseMySQL", $con);
mysql_query("SET NAMES 'utf8'");
$result = mysql_query("
select ima01,ima127,ima128,ima262_01,ima262_02 from mobile.IMA_FILE
where ima262_01+ima262_02 > 0
and ima127 = 0 and ima128 = 0
");
$fp = fopen('/tmp/MailNoPrice.csv', 'w');
fwrite($fp, iconv("UTF-8","big5","料號").",".iconv("UTF-8","big5","可出量")."\n");
while($row = mysql_fetch_assoc($result))
{
fwrite($fp, $row['ima01']);
fwrite($fp, ",");
fwrite($fp, $row['ima262_01'] + $row['ima262_02']);
fwrite($fp, "\n");
$GLOBALS['cnt'] += 1;
}
fclose($fp);
mysql_close($con);
}
function sendMail() {
require_once('sysmail.inc.php');
require_once('class.phpmailer.php');
$phpmail = new PHPMailer();
$phpmail->IsSMTP(true);
$phpmail->Host = $SysMail['SMTPhost'];
$phpmail->CharSet = "utf-8";
$phpmail->From = 'tyruan@echochem.com.tw';
$phpmail->FromName = 'MIS';
$phpmail->Subject = '有庫存,沒訂價 料號列表 (影響外網訂價)';
$html = "共計:" . $GLOBALS['cnt'] . "筆,請儘速修正。謝謝";
$phpmail->MsgHTML($html);
$phpmail->AddAttachment( "/tmp/MailNoPrice.csv" , 'MailNoPrice.csv' );
$phpmail->AddAddress( "tyruan@echochem.com.tw",'MIS' );
$phpmail->AddCC( "tyruan@echochem.com.tw",'MIS');
$phpmail->Send();
}
function main() {
getData();
if ($GLOBALS['cnt'] > 0) {
sendMail();
}
}
main();
?>
This man is too old to remember everything in his brain. Right now, he needs a place to write down what he has studied.
標籤
4GL
(1)
人才發展
(10)
人物
(3)
太陽能
(4)
心理
(3)
心靈
(10)
文學
(31)
生活常識
(14)
光學
(1)
名句
(10)
即時通訊軟體
(2)
奇狐
(2)
爬蟲
(1)
音樂
(2)
產業
(5)
郭語錄
(3)
無聊
(3)
統計
(4)
新聞
(1)
經濟學
(1)
經營管理
(42)
解析度
(1)
遊戲
(5)
電學
(1)
網管
(10)
廣告
(1)
數學
(1)
機率
(1)
雜趣
(1)
證券
(4)
證券期貨
(1)
ABAP
(15)
AD
(1)
agentflow
(4)
AJAX
(1)
Android
(1)
AnyChart
(1)
Apache
(14)
BASIS
(4)
BDL
(1)
C#
(1)
Church
(1)
CIE
(1)
CO
(38)
Converter
(1)
cron
(1)
CSS
(23)
DMS
(1)
DVD
(1)
Eclipse
(1)
English
(1)
excel
(5)
Exchange
(4)
Failover
(1)
Fedora
(1)
FI
(57)
File Transfer
(1)
Firefox
(3)
FM
(2)
fourjs
(1)
Genero
(1)
gladiatus
(1)
google
(1)
Google Maps API
(2)
grep
(1)
Grub
(1)
HR
(2)
html
(23)
HTS
(8)
IE
(1)
IE 8
(1)
IIS
(1)
IMAP
(3)
Internet Explorer
(1)
java
(4)
JavaScript
(22)
jQuery
(6)
JSON
(1)
K3b
(1)
ldd
(1)
LED
(3)
Linux
(120)
Linux Mint
(4)
Load Balance
(1)
Microsoft
(2)
MIS
(2)
MM
(51)
MSSQL
(1)
MySQL
(27)
Network
(1)
NFS
(1)
Office
(1)
OpenSSL
(1)
Oracle
(131)
Outlook
(3)
PDF
(6)
Perl
(60)
PHP
(33)
PL/SQL
(1)
PL/SQL Developer
(1)
PM
(3)
Postfix
(2)
postfwd
(1)
PostgreSQL
(1)
PP
(50)
python
(5)
QM
(1)
Red Hat
(4)
Reporting Service
(28)
ruby
(11)
SAP
(234)
scp
(1)
SD
(16)
sed
(1)
Selenium
(3)
Selenium-WebDriver
(5)
shell
(5)
SQL
(4)
SQL server
(8)
sqlplus
(1)
SQuirreL SQL Client
(1)
SSH
(3)
SWOT
(3)
Symantec
(2)
T-SQL
(7)
Tera Term
(2)
tip
(1)
tiptop
(24)
Tomcat
(6)
Trouble Shooting
(1)
Tuning
(5)
Ubuntu
(37)
ufw
(1)
utf-8
(1)
VIM
(11)
Virtual Machine
(2)
VirtualBox
(1)
vnc
(3)
Web Service
(2)
wget
(1)
Windows
(19)
Windows
(1)
WM
(6)
Xvfb
(2)
youtube
(1)
yum
(2)
2014年7月7日 星期一
2014年7月3日 星期四
定存股
http://knightkasim.pixnet.net/blog/post/37834438
郵局定存利率只有1%左右,利息相當微薄,因此,轉而投資定存股是不錯的選擇
定存股,顧名思義,就是把股票當作定存,每年領配股配息,挑到好的定存股,殖利率大於郵局定存利率
定存股需具備以下特性,不然很容易「賺了股利,賠了差價」
1. 比銀行定存利率高的殖利率:
殖利率=股利/股價
其中,股利=現金股利+股票股利
例如:今年中華電股價89.5元,現金股利5.4608元,股票股利0元,殖利率=(5.4608+0)/89.5=6.10%
也就是說,若以買一張中華電89.5元,配息5.4608元,獲利為6.10%,效率相當於郵局定存利率的6.1%/1.1%=5.55倍
投資同金額的情況下,5460.8元定存股只要一年,郵局定存卻要五年半才有這利息,或者郵局定存要比定存股多投入5.55倍金額才會有同等利息
要小心的是,若該股股價波動太大,從89.5元掉到80元,這樣配息賺了5460.8元,但股價卻賠了9500元,整體而言,賠了9500-5460.8=4039.2元,這就是「賺了股利,賠了差價」,所以只有殖利率高並不是好的定存股
2. 股價波動小與景氣循環相關度低:
承1,除了殖利率高之外,定存股還需具備股價波動小與景氣循環相關度低,否則會「賺了股利,賠了差價」。
例如:2412中華電景氣循環相關度就相當低,因為打電話、上網是無關景氣的,可以躺著賺
2002中鋼是景氣循環股,但股價波動小,故也是定存股
3. 配息穩定且不會倒閉
若公司倒閉,股票就變成廢紙了,錢就拿不回來了,故要選好公司;配息亦要穩定,否則一年有一年沒有,就比銀行定存還弱了。
4、可扣抵稅率高
一般來說,傳統產業股會有比較高的「扣抵稅率」,而高科技產業因為有租稅優惠,故「扣抵稅率」都不高。
兩稅合一將營利事業所得稅與綜合所稅兩種稅目合而為一了,故一般公司已先繳納營利事業所得稅,所以股東在領取股息時,可以用來扣抵個人綜所稅,而該股票依其「可扣抵稅率」來扣稅。
「可扣抵稅率」要高過「個人綜所稅率」才有節稅效果
例如:
1、王小明今年綜合所稅為20%,但中華電今年可扣抵稅率為17.46%,小明若參加除息,依照兩稅合一,股利要併入綜所稅申報,要補稅 20%-17.46%=2.54%,即補稅股利*2.54%的金額,若股利為10000元,則要補稅10000*2.54%=254元
2、王小明今年綜合所稅為12%,但中華電今年可扣抵稅率為17.46%,小明若參加除息,依照兩稅合一,可退稅17.46%-12%=5.46%,即退稅股利*5.46%的金額,若股利為10000元,則退稅10000*5.46%=546元
補充:定存利率對股價的影響
殖利率=無風險報酬+風險溢酬
其中,無風險報酬=銀行利率,風險溢酬即投資者可接受的報酬。
例如:
假設郵局定存利率為1.1%~10.1%,而風險溢酬為4%,穩定配息5元,則股價的變化為
由上圖可見,定存利率越高,投資者就傾向更低價購買該股,簡言之,若定存利率提高,投資者很容易會「賺了股利,賠了差價」,所幸,定存利率不太可能變動太大,也不會那麼高,故不用擔心。
相關文章:
[1]股票買賣手續費:說明股票手續費與證卷交易稅的計算公式,學會計算手續費與證交稅更能掌握股票損益平衡點
[2]定期定額懶人投資法:解釋定期定額微笑曲線的意義、優點與迷思,定期定額不是穩賺不賠,它只適用於懶人投資
[3]定價定額投資法:說明定價定額投資法的特點,此方法適用於定存股投資
[4]定存股票與一般股票的投資方法差異 :說明投資一般股票與定存股之間的差異,投資需慎選方法
[5]股票攤平策略與風險:說明投票攤平策略、操作方法與其風險
[6]ETF指數股票型基金:介紹ETF指數股票型基金的運作方法與風險
[7]零股買賣:說明零股買賣的相關事項
[8]二代健保補充保費:以實例說明二代健保補充保費如何計算
[9]簡單看懂證所稅:簡單了解證所稅的實施方法與計算證所稅實例
[10]複利才是致富的關鍵:說明單利與複利的意義,以及比較相同時間兩者的投資結果
[11]均線意義與多空判斷:說明均線意義,以及如何用均線判斷市場多空,避免與市場為敵而賠錢
[12]均線黃金交叉與死亡交叉應用:圖解說明均線黃金交叉與死亡交叉的應用,深入了解如何用均線判斷趨勢
[13]均線扣抵判斷均線未來走向:說明均線扣底的意義以及其應用,判斷均線未來走向
[14]台灣50 ETF0050投資法打敗定存 :台灣50簡易投資法,年報酬率可高於台幣定存
參考來源:
[1]http://www.masterhsiao.com.tw/Smart/SC159/SC159.php
[2]http://statementdog.com/blog/archives/479
2014年7月2日 星期三
MySQL Query Cache
http://blog.shian.tw/mysql-query-cache.html
MySQL 也有 cache可以使用! 提高資料庫效能有很重要的效用,可以節約大量的 CPU 時間 ,並且設定也非常的簡單,但是MySQL的版本要4以上才有這功能!!
設定:
1. 修改 /etc/my.cnf 檔案
# vi /etc/my.cnf
2.在 [mysqld] 裡加入下面這2行
query_cache_size=2m
query_cache_type = 1
註:
query_cache_type = 1 => 全部使用 query cache
query_cache_type = 2 => 選擇性使用或不使用 query cache
SELECT SQL_CACHE ‘*’ FROM table => 使用 query cache
SELECT SQL_NO_CACHE ‘*’ FROM table => 不使用 query cache
query_cache_size=2m : 設定cache大小
3. 重啟MySQL
# /etc/local/mysql/share/mysql/mysql.server restart
指令:
1. 查看是否有開啟 query cache
mysql> SHOW VARIABLES LIKE ‘have_query_cache’;
have_query_cache = YES 表示有開啟
2.查看緩衝的情況
mysql> show status like ‘Qca%’;
3.伺服器執行了多少 SELECT 語句
mysql> show status like ‘Com_sel%’;
實際測試:
使用 phpmyadmin 一次查詢五萬筆資料
未使用 query cache
第一次

第二次

第三次

第四次

第五次

使用 query cache
第一次

第二次

第三次

第四次

第五次

結論:
經過測試後發覺有使用 query ache 後, 第一次之後的查詢時間就明顯的減少很多,雖然看起來好像沒有減少多少,但是當資料量多或是更多人使用查詢時,效果就可以明顯感覺出來了, 而且這個測試只是五萬筆資料測試而已,
MySQL Query Cache
設定:
1. 修改 /etc/my.cnf 檔案
# vi /etc/my.cnf
2.在 [mysqld] 裡加入下面這2行
query_cache_size=2m
query_cache_type = 1
註:
query_cache_type = 1 => 全部使用 query cache
query_cache_type = 2 => 選擇性使用或不使用 query cache
SELECT SQL_CACHE ‘*’ FROM table => 使用 query cache
SELECT SQL_NO_CACHE ‘*’ FROM table => 不使用 query cache
query_cache_size=2m : 設定cache大小
3. 重啟MySQL
# /etc/local/mysql/share/mysql/mysql.server restart
指令:
1. 查看是否有開啟 query cache
mysql> SHOW VARIABLES LIKE ‘have_query_cache’;
have_query_cache = YES 表示有開啟
2.查看緩衝的情況
mysql> show status like ‘Qca%’;
3.伺服器執行了多少 SELECT 語句
mysql> show status like ‘Com_sel%’;
實際測試:
使用 phpmyadmin 一次查詢五萬筆資料
未使用 query cache
第一次
第二次
第三次
第四次
第五次
使用 query cache
第一次
第二次
第三次
第四次
第五次
結論:
經過測試後發覺有使用 query ache 後, 第一次之後的查詢時間就明顯的減少很多,雖然看起來好像沒有減少多少,但是當資料量多或是更多人使用查詢時,效果就可以明顯感覺出來了, 而且這個測試只是五萬筆資料測試而已,
MySQL資料庫簡易效能調教
http://www.cc.ntu.edu.tw/chinese/epaper/0025/20130620_2510.html
作者:游子興 / 臺灣大學計算機及資訊網路中心網路組幹事
本文將介紹兩種方法來改善資料庫之效能:
一. 使用 MySQLTuner 進行 MySQL 之整體參數改善分析
官方網站: http://mysqltuner.pl/mysqltuner.pl
目前的版本Version 1.2.0,支援 MySQL 資料庫版本:
MySQL 3.23, 4.0, 4.1, 5.0, 5.1 (full support)
MySQL 5.4 (not fully tested, partially supported)
MySQL 6.0 (partial support)
此程式主要的功能在於蒐集運行中的MySQL 之 STATUS 與 Variable 相關變數來判斷並提供改善建議,程式本身使用 Perl Script Language 撰寫,因此不需安裝,僅需下載執行即可。
Step1. 指令: wget http://mysqltuner.pl/mysqltuner.pl
登入 Linux 後下載 MySQLTuner 之執行檔案 mysqltuner.pl

圖1. 下載 MySQLTuner 之執行檔案 mysqltuner.pl
Step2. 指令: chmod +x mysqltuner.pl
因下載檔案預設無 Execute 執行權限,使用 chmod +x 增加 Execute 權限。
圖2. 使用 chmod +x 增加 Execute 權限
Step3. 指令: ./mysqltuner.pl
不需安裝,直接執行程式即可進行測試。程式會先要求輸入 MySQL 具有管理權限之帳號密碼,在此輸入 root 及其密碼。

圖3. 執行 mysqltuner.pl 並輸入帳號密碼
Step4. 分析執行結果
完全不需設定與安裝就可產生分析結果,是不是非常簡單?
圖4. mysqltuner.pl 執行結果報告
接著我們將逐步分析執行的結果,各項目分成綠色[OK]與紅色[!!]來顯示,我們僅需針對 紅色[!!] 的結果來做改善與調教:
(1)[!!] Switch to 64-bit OS - MySQL cannot currently use all of your RAM
因為32bit 之定址能力最高只到2^32= 4,294,967,296 (4G),若該 Server設備已安裝超過4G 之實體記憶體,則建議使用 64bit 之作業系統才能使用所有的記憶體。
(2)[!!] InnoDB is enabled but isn't being used
[!!] BDB is enabled but isn't being used
上述兩行的意思是 InnoDB 與 BDB 狀態為啟用,但並未使用,因此可搭配報告中最後的建議:
-------- Recommendations -----------------------------------------------------
General recommendations:
Add skip-innodb to MySQL configuration to disable InnoDB
Add skip-bdb to MySQL configuration to disable BDB
增加兩行設定到 MySQL 之設定檔 ( 以CentOS 5.5 為例,預設檔案為: /etc/my.cnf)
skip-innodb
skip-bdb

圖5. 編輯設定檔 /etc/my.cnf
之後需重新啟動 MySQL
~# service mysqld restart
(3)[!!] User '@localhost' has no password set.
[!!] User '@localhost.localdomain' has no password set.
上述兩行是指資料庫中有兩個帳號沒有設定密碼,可能有 Security Issue,經檢查Table: mysql.user 後發現,此兩個帳號預設為MySQL 安裝時所建立,並無 User 名稱也無設定權限,如下圖,因此可忽略此訊息。
圖6. 觀察 Table: mysql.user 所設定之帳號密碼
(4)[!!] Key buffer size / total MyISAM indexes: 8.0M/1.1G
此處點出了一個很重要的問題,就是 Key buffer size 太小(僅有 8.0M),參考報告中最後的建議:
-------- Recommendations -----------------------------------------------------
Variables to adjust:
key_buffer_size (> 1.1G)
建議將 key_buffer_size 由 8.0 M 調整至 1.1G,原因在於 Key buffer size 的作用在於 Cache Table中的 indexes(索引),目前的索引佔據的空間已有 1.1G ( /var/lib/mysql/ 目錄中索引檔案 *.MYI 之檔案大小加總),因此建議至少調高與目前之 indexes 大小相符。設定方法是增加一行設定到設定檔: /etc/my.cnf
key_buffer_size= 1100000000
設定後一樣需重新啟動 MySQL。
(5)[!!] Query cache is disabled
Query cache的作用在於 Cache 查詢(Query) 之結果以供後續相同的查詢使用,由變數query_cache_size 所控制,預設值為0,因此預設為 disabled,參考報告中最後的建議:
-------- Recommendations -----------------------------------------------------
Variables to adjust:
query_cache_size (>= 8M)
增加一行設定到 /etc/my.cnf
query_cache_size = 8000000
設定後一樣需重新啟動 MySQL。
(6)[!!] Thread cache is disabled
Thread cache的作用在於每次建立新的連線 (Thread) 時,會先看Thread cache 中是否有可用的 Thread,若有則直接取用,若無才重新建立新的連線,如此可減少CPU Loading。若系統常有大量且短暫的連線發生,則適當的設定此參數非常重要。由變數thread_cache_size 所控制,預設值為0,因此預設為 disabled,參考報告中最後的建議:
-------- Recommendations -----------------------------------------------------
Variables to adjust:
thread_cache_size (start at 4)
增加一行設定到 /etc/my.cnf
thread_cache_size=4
設定後一樣需重新啟動 MySQL,之後可用指令:
SHOW STATUS like 'Threads_%';
觀察變數 Threads_created 若已不會再持續增加,表示thread_cache_size已經足夠。

圖7. 觀察 STATUS 中 Threads 開頭之變數
(7)[!!] Connections aborted: 14%
此訊息搭配報告中最後的建議:
-------- Recommendations -----------------------------------------------------
General recommendations:
Your applications are not closing MySQL connections properly
表示時常有連上 MySQL 之連線不正常斷線,一般正常的斷線程式需呼叫mysql_close() 來正常關閉,可搭配指令:
SHOW STATUS like 'Aborted_%';

圖8. 觀察 STATUS 中 Aborted 開頭之變數
可觀察變數Aborted_clients, Aborted_connects 是否已經不再持續增加,來判斷是否已經改善。
(8)General recommendations:
MySQL started within last 24 hours - recommendations may be inaccurate
Enable the slow query log to troubleshoot bad queries
報告中最後還有兩個建議:
1.因為MySQLTuner 是利用 MySQL 系統中之 STATUS 與 Variable 相關變數來判斷並提供建議,因此必須有足夠的執行時間來蒐集資料庫運作的效能,因此若資料庫運作時間不到 24小時,則會出現警告訊息。
2.系統建議可開啟slow query log 之功能來記錄執行特別久的 SQL,以供後續的分析,方法為增加兩行設定到 /etc/my.cnf
log_slow_queries= mysqld-slow.log
long_query_time= 10
設定後一樣需重新啟動 MySQL。
log_slow_queries 指定 slow query log 存放之檔名,預設存在 /var/lib/mysql/ 目錄下。
long_query_time 設定超過幾秒之 SQL Query 會被記錄在 log_slow_queries 之log 檔中,系統預設值為 10秒。
二. 使用 Explain Plan 進行個別 SQL 調教
當資料庫的效能不符需求時,大部分發生在特定的 SQL 語句拖慢整個系統效能,蒐集這些 SQL 的方法本文提供兩種,一種就是用先前介紹的slow query log 方法記錄執行超過特定時間的 SQL,另一種方法是即時觀察系統目前之 Performance。
Step1. 指令: top

圖9. 使用 top 指令觀察系統資源使用情形
觀察CPU Usage%排名第一就是 mysqld,而且佔用了 99.9% 的 CPU Resource。
Step2. login MySQL,使用指令:
SHOW FULL PROCESSLIST;

圖10. 使用 SHOW FULL PROCESSLIST指令之執行結果
可看到目前正在執行之所有 SQL 語句,特別注意其中Process Id 8,Command 顯示 Query 表示正在執行,Time 欄位顯示已經執行了 117秒,Info 中有正在執行的 SQL 語句。
在得到了 SQL 語句之後,接著使用 Explain 觀察是否有可以改善之處.

圖11. 使用 Explain指令之執行結果
簡單說明各欄位之意義:
(1)select_type: SELECT 使用之語法型態。SIMPLE表示為簡單的查詢語句,也就是沒有 UNION、Subquery 等語法在此查詢中。
(2)table: 此 SQL 查詢所用到的 table,此案例因為使用了 Join因此用到了兩個 table。
(3)type: 使用何種類型進行查詢。最優至最差的類型為:
system -> const -> eq_ref -> ref -> fulltext -> ref_or_null -> index_merge -> unique_subquery -> index_subquery -> range -> index -> ALL
此案例值為”ALL”,也就是最差之狀況。
(4)possible_keys:可能使用的索引欄位。若為NULL 表示無索引可使用。
(5)key:實際使用的索引欄位。若為NULL 表示無索引可使用。
(6)key_len:使用的索引長度。
(7)rows: SQL 必須搜尋的資料筆數。
(8)Extra:
Using where: SQL 中有使用WHERE 語句來限制查詢的範圍。
Using temporary : MySQL 必須建立一個臨時的 Table 來儲存查詢結果,通常發生在 SQL 語法中有 Order By 或 GROUP BY。
Using filesort:MySQL必須進行額外的步驟來進行 ORDER BY 之排序作業。
此段 SQL 執行之狀況,也可參考前面第一部分之介紹啟用slow query log,log 記錄檔中顯示:
/var/lib/mysql/mysqld-slow.log

圖12. slow query log 記錄之內容
此 SQL 共花了 121 秒才執行完成。
由上述的Explain 分析可知,此段 SQL 並未使用任何的索引,我們再次分析此段 SQL 中 JOIN 與 WHERE 條件中所出現的欄位:
LEFT JOIN … ON aruba.ArubaLocationID = arubalocationmap.ArubaLocationID
WHERE (YEAR(`AcctStartTime`) > '2012'…..
AND aruba.`ArubaLocationID` LIKE '113.%' ….
其中特別注意的是 JOIN 語法中兩個 Table 的對應欄位都必須加上索引才有作用,因此我們決定針對
Table: aruba 增加 ArubaLocationID, AcctStartTime 兩個欄位的索引
Table: arubalocationmap增加 ArubaLocationID 一個欄位的索引
建立索引的語法如下:
CREATE Index ArubaLocationID On aruba (ArubaLocationID);
CREATE Index AcctStartTime On aruba (AcctStartTime);
CREATE Index ArubaLocationID On arubalocationmap (ArubaLocationID);
索引建立後,我們再次使用 Explain 觀察此段 SQL 執行之情況:


圖13. 使用 Explain指令之執行結果
由 type, key 欄位發現新建的索引已經發揮作用。
再次檢查 slow query log,log 記錄檔中顯示:
/var/lib/mysql/mysqld-slow.log

圖14. slow query log 記錄之內容
執行時間由 121 秒減少為 13秒,僅需原來 1/10的時間,由此可知建立正確的索引將有非常大幅度之改善。
結論
MySQL 是個功能強大的資料庫,尤其搭配 PHP 程式後可做出各式的動態網頁資料庫進行各類的應用,本文拋磚引玉使用簡單的範例來調整並改善資料庫的效能,投入的時間與改善並不需要太久,但卻能有十倍之 執行效能改善,這樣的改善效益是非常令人期待的。
參考資料
1. MySQLTuner http://mysqltuner.pl/
2. Explain plan http://dev.mysql.com/doc/refman/5.0/en/explain-output.html 3.query cache size (query_cache_size) http://dev.mysql.com/doc/refman/5.0/en/query-cache-configuration.html
作者:游子興 / 臺灣大學計算機及資訊網路中心網路組幹事
MySQL 資料庫是個使用廣泛的 Open Source 資料庫,本文以實際的範例搭配淺顯的說明與實作,一步一步進行效能之調教,而使大部分非科班出生之 MySQL 資料庫管理人員得以輕鬆應付與日遽增大量的資料。
前言
MySQL 是一個Open Source的中小型關連式資料庫,因本身簡單易用且大部分的 Linux Distribution 皆有提供 MySQL Package,因此許多學術單位與中小型企業十分愛用。但隨著時間增加,資料量也持續增加,如何作效能之調教與改善 (Performance Tuning) 對於可能非科班出生之資料庫管理員 DBA,則成為一個棘手的問題。 本文將介紹兩種方法來改善資料庫之
MySQL
是一個Open Source的中小型關連式資料庫,因本身簡單易用且大部分的 Linux Distribution 皆有提供 MySQL
Package,因此許多學術單位與中小型企業十分愛用。但隨著時間增加,資料量也持續增加,如何作效能之調教與改善 (Performance
Tuning) 對於可能非科班出生之資料庫管理員 DBA,則成為一個棘手的問題。 MySQL 是一個Open Source的中小型關連式資料庫,因本身簡單易用且大部分的 Linux Distribution 皆有提供 MySQL Package,因此許多學術單位與中小型企業十分愛用。但隨著時間增加,資料量也持續增加,如何作效能之調教與改善 (Performance Tuning) 對於可能非科班出生之資料庫管理員 DBA,則成為一個棘手的問題。 本文將介紹兩種方法來改善資料庫之
本文將介紹兩種方法來改善資料庫之效能:
- 使用 MySQLTuner 進行 MySQL 之整體參數改善分析
- 使用 Explain Plan 進行個別 SQL 調教
一. 使用 MySQLTuner 進行 MySQL 之整體參數改善分析
官方網站: http://mysqltuner.pl/mysqltuner.pl
目前的版本Version 1.2.0,支援 MySQL 資料庫版本:
MySQL 3.23, 4.0, 4.1, 5.0, 5.1 (full support)
MySQL 5.4 (not fully tested, partially supported)
MySQL 6.0 (partial support)
此程式主要的功能在於蒐集運行中的MySQL 之 STATUS 與 Variable 相關變數來判斷並提供改善建議,程式本身使用 Perl Script Language 撰寫,因此不需安裝,僅需下載執行即可。
Step1. 指令: wget http://mysqltuner.pl/mysqltuner.pl
登入 Linux 後下載 MySQLTuner 之執行檔案 mysqltuner.pl
圖1. 下載 MySQLTuner 之執行檔案 mysqltuner.pl
Step2. 指令: chmod +x mysqltuner.pl
因下載檔案預設無 Execute 執行權限,使用 chmod +x 增加 Execute 權限。
圖2. 使用 chmod +x 增加 Execute 權限
Step3. 指令: ./mysqltuner.pl
不需安裝,直接執行程式即可進行測試。程式會先要求輸入 MySQL 具有管理權限之帳號密碼,在此輸入 root 及其密碼。
圖3. 執行 mysqltuner.pl 並輸入帳號密碼
Step4. 分析執行結果
完全不需設定與安裝就可產生分析結果,是不是非常簡單?
圖4. mysqltuner.pl 執行結果報告
接著我們將逐步分析執行的結果,各項目分成綠色[OK]與紅色[!!]來顯示,我們僅需針對 紅色[!!] 的結果來做改善與調教:
(1)[!!] Switch to 64-bit OS - MySQL cannot currently use all of your RAM
因為32bit 之定址能力最高只到2^32= 4,294,967,296 (4G),若該 Server設備已安裝超過4G 之實體記憶體,則建議使用 64bit 之作業系統才能使用所有的記憶體。
(2)[!!] InnoDB is enabled but isn't being used
[!!] BDB is enabled but isn't being used
上述兩行的意思是 InnoDB 與 BDB 狀態為啟用,但並未使用,因此可搭配報告中最後的建議:
-------- Recommendations -----------------------------------------------------
General recommendations:
Add skip-innodb to MySQL configuration to disable InnoDB
Add skip-bdb to MySQL configuration to disable BDB
增加兩行設定到 MySQL 之設定檔 ( 以CentOS 5.5 為例,預設檔案為: /etc/my.cnf)
skip-innodb
skip-bdb
圖5. 編輯設定檔 /etc/my.cnf
之後需重新啟動 MySQL
~# service mysqld restart
(3)[!!] User '@localhost' has no password set.
[!!] User '@localhost.localdomain' has no password set.
上述兩行是指資料庫中有兩個帳號沒有設定密碼,可能有 Security Issue,經檢查Table: mysql.user 後發現,此兩個帳號預設為MySQL 安裝時所建立,並無 User 名稱也無設定權限,如下圖,因此可忽略此訊息。
圖6. 觀察 Table: mysql.user 所設定之帳號密碼
(4)[!!] Key buffer size / total MyISAM indexes: 8.0M/1.1G
此處點出了一個很重要的問題,就是 Key buffer size 太小(僅有 8.0M),參考報告中最後的建議:
-------- Recommendations -----------------------------------------------------
Variables to adjust:
key_buffer_size (> 1.1G)
建議將 key_buffer_size 由 8.0 M 調整至 1.1G,原因在於 Key buffer size 的作用在於 Cache Table中的 indexes(索引),目前的索引佔據的空間已有 1.1G ( /var/lib/mysql/ 目錄中索引檔案 *.MYI 之檔案大小加總),因此建議至少調高與目前之 indexes 大小相符。設定方法是增加一行設定到設定檔: /etc/my.cnf
key_buffer_size= 1100000000
設定後一樣需重新啟動 MySQL。
(5)[!!] Query cache is disabled
Query cache的作用在於 Cache 查詢(Query) 之結果以供後續相同的查詢使用,由變數query_cache_size 所控制,預設值為0,因此預設為 disabled,參考報告中最後的建議:
-------- Recommendations -----------------------------------------------------
Variables to adjust:
query_cache_size (>= 8M)
增加一行設定到 /etc/my.cnf
query_cache_size = 8000000
設定後一樣需重新啟動 MySQL。
(6)[!!] Thread cache is disabled
Thread cache的作用在於每次建立新的連線 (Thread) 時,會先看Thread cache 中是否有可用的 Thread,若有則直接取用,若無才重新建立新的連線,如此可減少CPU Loading。若系統常有大量且短暫的連線發生,則適當的設定此參數非常重要。由變數thread_cache_size 所控制,預設值為0,因此預設為 disabled,參考報告中最後的建議:
-------- Recommendations -----------------------------------------------------
Variables to adjust:
thread_cache_size (start at 4)
增加一行設定到 /etc/my.cnf
thread_cache_size=4
設定後一樣需重新啟動 MySQL,之後可用指令:
SHOW STATUS like 'Threads_%';
觀察變數 Threads_created 若已不會再持續增加,表示thread_cache_size已經足夠。
圖7. 觀察 STATUS 中 Threads 開頭之變數
(7)[!!] Connections aborted: 14%
此訊息搭配報告中最後的建議:
-------- Recommendations -----------------------------------------------------
General recommendations:
Your applications are not closing MySQL connections properly
表示時常有連上 MySQL 之連線不正常斷線,一般正常的斷線程式需呼叫mysql_close() 來正常關閉,可搭配指令:
SHOW STATUS like 'Aborted_%';
圖8. 觀察 STATUS 中 Aborted 開頭之變數
可觀察變數Aborted_clients, Aborted_connects 是否已經不再持續增加,來判斷是否已經改善。
(8)General recommendations:
MySQL started within last 24 hours - recommendations may be inaccurate
Enable the slow query log to troubleshoot bad queries
報告中最後還有兩個建議:
1.因為MySQLTuner 是利用 MySQL 系統中之 STATUS 與 Variable 相關變數來判斷並提供建議,因此必須有足夠的執行時間來蒐集資料庫運作的效能,因此若資料庫運作時間不到 24小時,則會出現警告訊息。
2.系統建議可開啟slow query log 之功能來記錄執行特別久的 SQL,以供後續的分析,方法為增加兩行設定到 /etc/my.cnf
log_slow_queries= mysqld-slow.log
long_query_time= 10
設定後一樣需重新啟動 MySQL。
log_slow_queries 指定 slow query log 存放之檔名,預設存在 /var/lib/mysql/ 目錄下。
long_query_time 設定超過幾秒之 SQL Query 會被記錄在 log_slow_queries 之log 檔中,系統預設值為 10秒。
二. 使用 Explain Plan 進行個別 SQL 調教
當資料庫的效能不符需求時,大部分發生在特定的 SQL 語句拖慢整個系統效能,蒐集這些 SQL 的方法本文提供兩種,一種就是用先前介紹的slow query log 方法記錄執行超過特定時間的 SQL,另一種方法是即時觀察系統目前之 Performance。
Step1. 指令: top
圖9. 使用 top 指令觀察系統資源使用情形
觀察CPU Usage%排名第一就是 mysqld,而且佔用了 99.9% 的 CPU Resource。
Step2. login MySQL,使用指令:
SHOW FULL PROCESSLIST;
圖10. 使用 SHOW FULL PROCESSLIST指令之執行結果
可看到目前正在執行之所有 SQL 語句,特別注意其中Process Id 8,Command 顯示 Query 表示正在執行,Time 欄位顯示已經執行了 117秒,Info 中有正在執行的 SQL 語句。
在得到了 SQL 語句之後,接著使用 Explain 觀察是否有可以改善之處.
圖11. 使用 Explain指令之執行結果
簡單說明各欄位之意義:
(1)select_type: SELECT 使用之語法型態。SIMPLE表示為簡單的查詢語句,也就是沒有 UNION、Subquery 等語法在此查詢中。
(2)table: 此 SQL 查詢所用到的 table,此案例因為使用了 Join因此用到了兩個 table。
(3)type: 使用何種類型進行查詢。最優至最差的類型為:
system -> const -> eq_ref -> ref -> fulltext -> ref_or_null -> index_merge -> unique_subquery -> index_subquery -> range -> index -> ALL
此案例值為”ALL”,也就是最差之狀況。
(4)possible_keys:可能使用的索引欄位。若為NULL 表示無索引可使用。
(5)key:實際使用的索引欄位。若為NULL 表示無索引可使用。
(6)key_len:使用的索引長度。
(7)rows: SQL 必須搜尋的資料筆數。
(8)Extra:
Using where: SQL 中有使用WHERE 語句來限制查詢的範圍。
Using temporary : MySQL 必須建立一個臨時的 Table 來儲存查詢結果,通常發生在 SQL 語法中有 Order By 或 GROUP BY。
Using filesort:MySQL必須進行額外的步驟來進行 ORDER BY 之排序作業。
此段 SQL 執行之狀況,也可參考前面第一部分之介紹啟用slow query log,log 記錄檔中顯示:
/var/lib/mysql/mysqld-slow.log
圖12. slow query log 記錄之內容
此 SQL 共花了 121 秒才執行完成。
由上述的Explain 分析可知,此段 SQL 並未使用任何的索引,我們再次分析此段 SQL 中 JOIN 與 WHERE 條件中所出現的欄位:
LEFT JOIN … ON aruba.ArubaLocationID = arubalocationmap.ArubaLocationID
WHERE (YEAR(`AcctStartTime`) > '2012'…..
AND aruba.`ArubaLocationID` LIKE '113.%' ….
其中特別注意的是 JOIN 語法中兩個 Table 的對應欄位都必須加上索引才有作用,因此我們決定針對
Table: aruba 增加 ArubaLocationID, AcctStartTime 兩個欄位的索引
Table: arubalocationmap增加 ArubaLocationID 一個欄位的索引
建立索引的語法如下:
CREATE Index ArubaLocationID On aruba (ArubaLocationID);
CREATE Index AcctStartTime On aruba (AcctStartTime);
CREATE Index ArubaLocationID On arubalocationmap (ArubaLocationID);
索引建立後,我們再次使用 Explain 觀察此段 SQL 執行之情況:
圖13. 使用 Explain指令之執行結果
由 type, key 欄位發現新建的索引已經發揮作用。
再次檢查 slow query log,log 記錄檔中顯示:
/var/lib/mysql/mysqld-slow.log
圖14. slow query log 記錄之內容
執行時間由 121 秒減少為 13秒,僅需原來 1/10的時間,由此可知建立正確的索引將有非常大幅度之改善。
結論
MySQL 是個功能強大的資料庫,尤其搭配 PHP 程式後可做出各式的動態網頁資料庫進行各類的應用,本文拋磚引玉使用簡單的範例來調整並改善資料庫的效能,投入的時間與改善並不需要太久,但卻能有十倍之 執行效能改善,這樣的改善效益是非常令人期待的。
參考資料
1. MySQLTuner http://mysqltuner.pl/
2. Explain plan http://dev.mysql.com/doc/refman/5.0/en/explain-output.html 3.query cache size (query_cache_size) http://dev.mysql.com/doc/refman/5.0/en/query-cache-configuration.html
MySQL 設定檔優化-cache
http://article.denniswave.com/6345
From:http://www.bsdlover.cn/html/89/n-1789.html
查詢Cache狀態
例如現在我們查詢的結果如下:
設置為64M cache內存後
自由內存塊看起來變小了。
是因為現在自由內存塊是一個整塊,而以前的內存塊都是分散的小塊。而因為重建了cache區,Qcache_queries_in_cache 變量變小了。因為此操作重新建立了cache內存區,所有數據重新緩存,在運行一兩天後我們再看此數據。如果變大了,說明增大cache內存區域是有效 的,如果和以前數據差不多說明增加的內存並沒有實際起到多大的作用。
有人會覺得如果我將cache內存設置的非常大,然後將cache_limit設置成0,那麼所有查詢都會被緩存了。理論上是這樣,但是一台數據庫 服務器的查詢非常多,如果連查詢單條數據都要緩存,那麼內存再大也會不夠的。到時候老的內容就會被交換出去,當cache內存使用滿的時候,就會不停的有 新查詢進來將老查詢替換出去。
這樣導致兩個結果:一個是內存顛簸,效率反而下降;第二個是cache內存的小碎塊增多,內存利用率降低。如果是只有內容很少的小庫,並且查詢率不高,是可以使用這種方法提高響應速度。但是如果是實際生產環境,數據量會比較大,還是需要按照最佳比例來配置。
而不同的應用不同的數據量會有不同的搭配,這點大家不要看網上的優化配置隨便的填寫,還是要時時的查看mysql的狀態進行調整。即便是這個月調整好的優化參數,到了下個月業務不同,數據量增加,也會需要調整的。
From:http://www.bsdlover.cn/html/89/n-1789.html
- thread_concurrency 數量設置為CPU核心數量的兩倍.
- thread_cache_size 按照內存大小來設置, 1G=8, 2G=16, 3G=32, >3G=64
- wait_timeout 超時時間,如果連接數比較大,可以減少此參數的值,我使用的是10
- max_connections 最大連接數,mysql實際允許連接數的值是max_connections+1,按照系統庫不同而有不同性能。一般是500~1000,MySQL AB提供的linux靜態庫可以達到4000。
- query_cache_size 查詢緩衝,默認是0,所以必須打開以提高mysql性能,其本身需要40K來保存結構數據。所以不能設置的太小,初期可以設置成32M,然後根據實際運行情況另行調整。
- query_cache_type 指定查詢緩衝的類型:
- query_cache_limit 允許進入查詢緩衝區的最小數據大小,默認值是1MB,可以修改的小一點以滿足更多查詢的需求。但是如果設置的過於小,則會導致很多新的小查詢的結果將原有的查詢結果交換出去,增加系統的顛簸。
0是關閉
1是緩衝除了使用 SELECT SQL_NO_CACHE 語句指明了不需要緩衝的數據意外的所有查詢
2是只緩衝 SELECT SQL_CACHE 指定的查詢
一般設置為1
- 查詢mysql服務器相關狀態數據 >SHOW STATUS;
- 查詢mysql服務器相關配置選項 >SHOW VARIABLES;
- 整理查詢緩衝區裡的碎片 >flush query cache;
- 刪除查詢緩衝區裡的所有內容 >reset query cache;
- 設置mysql參數 >SET GLOBAL;
- 查詢mysql當前執行的sql語句 >show processlist;
- 查詢緩存中的空閒內存塊的數目 Qcache_free_blocks
- 查詢緩存的空閒內存總數 Qcache_free_memory
- 緩存採樣數數目 Qcache_hits
- 被加入到緩存中的查詢數目 Qcache_inserts
- 因為缺少內存而被從緩存中刪除的查詢數目 Qcache_lowmem_prunes
- 沒有被緩存的查詢數目 (不能被緩存的,或由於 QUERY_CACHE_TYPE) Qcache_not_cached
- 在緩存中已註冊的查詢數目 Qcache_queries_in_cache
- 查詢緩存中的塊的總數目 Qcache_total_blocks
查詢Cache狀態
如果Qcache_lowmem_prunes非常大,說明因為內存不足而被交換出cache的數據很多.如果增加內存.可以保證較小的交換次數以及較高的命中率>SHOW STATUS LIKE 'Qcache%';
例如現在我們查詢的結果如下:
| Qcache_free_blocks | 1234 |
| Qcache_free_memory | 25957504 |
| Qcache_hits | 55771119 |
| Qcache_inserts | 7441153 |
| Qcache_lowmem_prunes | 28332 |
| Qcache_not_cached | 1233788 |
| Qcache_queries_in_cache | 4810 |
| Qcache_total_blocks | 11038 |
>set global query_cache_size=67108864;
| Qcache_free_blocks | 1 |
| Qcache_free_memory | 66623616 |
| Qcache_hits | 55788258 |
| Qcache_inserts | 7445445 |
| Qcache_lowmem_prunes | 28332 |
| Qcache_not_cached | 1234057 |
| Qcache_queries_in_cache | 183 |
| Qcache_total_blocks | 392 |
是因為現在自由內存塊是一個整塊,而以前的內存塊都是分散的小塊。而因為重建了cache區,Qcache_queries_in_cache 變量變小了。因為此操作重新建立了cache內存區,所有數據重新緩存,在運行一兩天後我們再看此數據。如果變大了,說明增大cache內存區域是有效 的,如果和以前數據差不多說明增加的內存並沒有實際起到多大的作用。
有人會覺得如果我將cache內存設置的非常大,然後將cache_limit設置成0,那麼所有查詢都會被緩存了。理論上是這樣,但是一台數據庫 服務器的查詢非常多,如果連查詢單條數據都要緩存,那麼內存再大也會不夠的。到時候老的內容就會被交換出去,當cache內存使用滿的時候,就會不停的有 新查詢進來將老查詢替換出去。
這樣導致兩個結果:一個是內存顛簸,效率反而下降;第二個是cache內存的小碎塊增多,內存利用率降低。如果是只有內容很少的小庫,並且查詢率不高,是可以使用這種方法提高響應速度。但是如果是實際生產環境,數據量會比較大,還是需要按照最佳比例來配置。
而不同的應用不同的數據量會有不同的搭配,這點大家不要看網上的優化配置隨便的填寫,還是要時時的查看mysql的狀態進行調整。即便是這個月調整好的優化參數,到了下個月業務不同,數據量增加,也會需要調整的。
2014年7月1日 星期二
PHP中查看错误log
http://blog.csdn.net/hopestar2/article/details/5960616
php中需要查看错误log,如何设置?
首先需要在php.ini打开开关和制定错误log路径
log_errors = On
error_log = d://phperror.log //windows下的设置
如果是在linux 下,使用lighttpd服务器,则可以使用如下方式查看log文件
tail -n 20 /usr/local/lighttpd/log/php-error.log
在php代码中如何记录log,在PHP官方文档中有个函数error_log(),使用方法如下:
若成功,返回 true,否则返回 false。
php中需要查看错误log,如何设置?
首先需要在php.ini打开开关和制定错误log路径
log_errors = On
error_log = d://phperror.log //windows下的设置
如果是在linux 下,使用lighttpd服务器,则可以使用如下方式查看log文件
tail -n 20 /usr/local/lighttpd/log/php-error.log
在php代码中如何记录log,在PHP官方文档中有个函数error_log(),使用方法如下:
定义和用法
error_log() 函数向服务器错误记录、文件或远程目标发送一个错误。若成功,返回 true,否则返回 false。
语法
error_log(error,type,destination,headers)
| 参数 | 描述 |
|---|---|
| error | 必需。要记录的错误消息。 |
| type |
可选。规定错误记录的类型。 可能的记录类型:
|
| destination | 可选。规定向何处发送错误消息。该参数的值依赖于 "type" 参数的值。 |
| headers |
可选。只在 "type" 为 1 时使用。 规定附加的头部,比如 From, Cc 以及 Bcc。由 CRLF (/r/n) 分隔。 注释:在发送电子邮件时,必须包含 From 头部。可以在 php.ini 文件中或者通过此参数设置。 |
例子
本例发送一封带有自定义错误的电子邮件:<?php
$test=2;
if ($test>1)
{
error_log("A custom error has been triggered",
1,"someone@example.com","From: webmaster@example.com");
}
?>
输出:A custom error has been triggered
PS: 在调试php代码的时候,除了使用error_log()函数,还可以使用 throw new Exception()抛出异常信息。
PHP logging
http://www.devshed.com/c/a/php/logging-with-php/
This entry was posted in PHP. Bookmark the permalink.
Logging With PHP
Posted on by seo-admin
Want to log script activity in your Web application, but have
no clue where to begin? Take our handy tour of PHP’s logging functions,
and find out how simple it really is.
I have to warn you not to be misled by the title of this article. It isn’t really about cutting down trees with PHP.
I know that PHP is the Swiss Army knife of Web scripting languages, but I don’t think its developers have come up with a way to have it reduce our tree cover (at least not yet). Rather, this article is about a different sort of logging – the sort which involves writing messages to files or devices on a regular basis, and using these messages to “do something useful”, be it generating a report or building an audit trail for activity tracking.
Over the next few pages, I’m going to take a quick look at the various mechanisms available to log script activity via PHP, demonstrating both built-in functions and add-on classes that allow you to add logging functionality to your applications. I’ll also spend some time on the PHP functions and configuration options related to logging, demonstrating how, for example, PHP errors can be sent to the Web server error log or emailed to an administrator when they are over a particular priority level.
My primary audience for this tutorial is the novice to intermediate PHP user – if you’re an advanced user, you probably already know enough about logging with PHP, and might prefer to skip the rest of this article in favour of more nutritious fare. Everyone else – keep reading!{mospagebreak title=The Bare Necessities} Logging data to a file in PHP can be as simple or as complex as you want to make it. Break it down, though, and it all comes down to these three simple lines of code:
1. Open the target file (or create it if it doesn’t already exist);
2. Append your data to the end of the file;
3. Close the file.
You can encapsulate this as a function,
In order to illustrate this, consider the following example of an SQL table used to store log messages:
Another option might be to send log messages to a specified email address via PHP’s mail() function – for example, alerting a sysop whenever a script encounters errors. Here’s an example:
0 – send the message to the system logger (“syslogd” on *NIX, and the Event Log on Windows NT);
1 – send the message to the specified email address;
3 – send the message to the specified file;
Here’s a trivial example which demonstrates how this works:
Like the error_log() function, the PEAR Log class allows logging to a variety of different destinations – system logger, text file, email address, database and even MCAL. Here’s an example demonstrating basic usage:
Consider the following example, which demonstrates:
On *NIX systems, setting the “error_log” variable to the special value “syslog” logs all errors via the standard “syslog” daemon.{mospagebreak title=Big Brother Is Watching} Finally, let’s wrap things up with a couple of examples that show how the various techniques demonstrated above can be used to build logs and audit trails for a Web application.
In the first example, every time a Web page is displayed, a log entry is made in an “access.log” file. This log entry is a comma-separated list of values containing the URL requested, the client browser identification string, and a timestamp.
Consider this next example, which provides an API for adding, editing and deleting users to (from) a Web application. Each time the user database is edited, a separate audit() process tracks the change, logging both the nature of the change and information about the user initiating the change. This log data is stored in a separate SQL table, from where it can be retrieved for statistical reporting, user activity monitoring or debugging.
I hope you enjoyed reading this article as much as I enjoyed writing it. If you’d like to know more about the topics discussed in the previous pages, here are some links you should bookmark:
PHP file manipulation functions, at http://www.php.net/manual/en/ref.filesystem.php
PHP mail functions, at http://www.php.net/manual/en/ref.mail.php
PHP MySQL functions, at http://www.php.net/manual/en/ref.mysql.php
PHP error logging functions, at http://www.php.net/manual/en/ref.errorfunc.php
The PHP Log class, at http://pear.php.net/package-info.php?package=Log
PEAR, at http://pear.php.net
Till next time…stay healthy!
Note: All examples in this article have been tested on Linux/i586 with PHP 4.2.3. Examples are illustrative only, and are not meant for a production environment. Melonfire provides no warranties or support for the source code described in this article. YMMV!
I have to warn you not to be misled by the title of this article. It isn’t really about cutting down trees with PHP.
I know that PHP is the Swiss Army knife of Web scripting languages, but I don’t think its developers have come up with a way to have it reduce our tree cover (at least not yet). Rather, this article is about a different sort of logging – the sort which involves writing messages to files or devices on a regular basis, and using these messages to “do something useful”, be it generating a report or building an audit trail for activity tracking.
Over the next few pages, I’m going to take a quick look at the various mechanisms available to log script activity via PHP, demonstrating both built-in functions and add-on classes that allow you to add logging functionality to your applications. I’ll also spend some time on the PHP functions and configuration options related to logging, demonstrating how, for example, PHP errors can be sent to the Web server error log or emailed to an administrator when they are over a particular priority level.
My primary audience for this tutorial is the novice to intermediate PHP user – if you’re an advanced user, you probably already know enough about logging with PHP, and might prefer to skip the rest of this article in favour of more nutritious fare. Everyone else – keep reading!{mospagebreak title=The Bare Necessities} Logging data to a file in PHP can be as simple or as complex as you want to make it. Break it down, though, and it all comes down to these three simple lines of code:
Fundamentally, logging data to a file consists of three steps:
<?php // open file $fd = fopen($filename, “a”); // write string fwrite($fd, $str . “n”); // close file fclose($fd); ?>
1. Open the target file (or create it if it doesn’t already exist);
2. Append your data to the end of the file;
3. Close the file.
You can encapsulate this as a function,
and then use it liberally within your code as and when required.
<?php function logToFile($filename, $msg) { // open file $fd = fopen($filename, “a”); // write string fwrite($fd, $msg . “n”); // close file fclose($fd); } ?>
You can make the function a little more professional by having it automatically append the date and time of the log message to the log file as well:
<?php function logToFile($filename, $msg) { // open file $fd = fopen($filename, “a”); // write string fwrite($fd, $msg . “n”); // close file fclose($fd); } $v = “Mary had a little lamb”; if (!is_numeric($v)) { logToFile(“my.log”, “Non-numeric variable encountered”); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { logToFile(“my.log”, “No fish available”); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { logToFile(“my.log”, “Could not connect to database”); die(“Could not connect to database”); } ?>
Here’s an example of the output:
<?php function logToFile($filename, $msg) { // open file $fd = fopen($filename, “a”); // append date/time to message $str = “[" . date("Y/m/d h:i:s", mktime()) . "] ” . $msg; // write string fwrite($fd, $str . “n”); // close file fclose($fd); } ?>
{mospagebreak title=Turning The Tables} While the most common destination for log data is a text file, it’s quite possible that you might want to send your log messages elsewhere as well. A frequently-used alternative to a text file, especially when the number of writes isn’t too high, is an SQL database, where log messages are appended as records to the end of a table.
[2002/11/25 06:02:42] Non-numeric variable encountered [2002/11/25 06:02:42] No fish available [2002/11/25 06:02:43] Could not connect to database
In order to illustrate this, consider the following example of an SQL table used to store log messages:
And here’s the rewritten logToDB() function, this time built around PHP’s MySQL database functions and the table above:
CREATE TABLE `log` ( `date` TIMESTAMP NOT NULL, `type` TINYINT NOT NULL, `msg` VARCHAR(255) NOT NULL );
If you don’t estimate seeing a very large number of writes, using a database to store logs can offer significant advantages over a regular file, purely from the point of view of easier retrieval and sorting. Storing log messages in this manner makes it possible to easily retrieve ordered subsets of the log data, either by date or message type.
function logToDB($msg, $type) { // open connection to database $connection = mysql_connect(“localhost”, “joe”, “pass”) or die (“Unable to connect!”); mysql_select_db(“logdb”) or die (“Unable to select database!”); // formulate and execute query $query = “INSERT INTO log (date, type, msg) VALUES(NOW(), ‘$type’, ‘$msg’)”; mysql_query($query) or die (“Error in query: $query. ” . mysql_error()); // close connection mysql_close($connection); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { logToDB(“No fish available”, 14); }
Another option might be to send log messages to a specified email address via PHP’s mail() function – for example, alerting a sysop whenever a script encounters errors. Here’s an example:
{mospagebreak title=Turning Up The Heat} If the thought of rolling your own code doesn’t appeal to you, you can also use PHP’s built-in error_log() function, which logs data both to a file and elsewhere. The error_log() function needs a minimum of two arguments: the error message to be logged, and an integer indicating where the message should be sent. There are three possible integer values in PHP 4.x:
function logToMail($msg, $address) { // append date/time to message $str = “[" . date("Y/m/d h:i:s", mktime()) . "] ” . $msg; mail($address, “Log message”, $str); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { logToMail(“Could not connect to database”, “webmaster@my.domain.name.com”); }
0 – send the message to the system logger (“syslogd” on *NIX, and the Event Log on Windows NT);
1 – send the message to the specified email address;
3 – send the message to the specified file;
Here’s a trivial example which demonstrates how this works:
Now, if you look at the system log file after running the script, you’ll see something like this:
<?php // set a variable $temp = 101.6; // test it and log an error // this will only work if // you have “log_errors” and “error_log” set in your php.ini file if ($temp > 98.6) { error_log(“Body temperature above normal.”, 0); } ?>
You can also write the error message to a file,
[28-Feb-2002 15:50:49] Body temperature above normal.
or send it out as email.
<?php // set a variable $temp = 101.6; // test it and log an error if ($temp > 98.6) { error_log(“Body temperature above normal.”, 3, “a.out”); } ?>
It’s possible to combine this error logging facility with a custom error handler to ensure that all script errors get logged to a file. Here’s an example which demonstrates this:
<?php // set a variable $temp = 101.6; // test it and log an error if ($temp > 98.6) { error_log(“Body temperature above normal.”, 1, “administrator@this.body.com”); } ?>
And here’s the output that gets logged to the system log file:
<?php // custom handler function eh($type, $msg, $file, $line) { // log all errors error_log(“$msg (error type $type)”, 0); // if fatal error, die() if ($type == E_USER_ERROR) { die($msg); } } // report all errors error_reporting(E_ALL); // define custom handler set_error_handler(“eh”); // let’s now write some bad code // this will trigger a warning, since the file doesn’t exist include(“common.php”); ?>
{mospagebreak title=Biting Into A PEAR} As if all that wasn’t enough, PHP offers one more alternative – a special Log class that comes courtesy of PEAR, the PHP Extension and Application Repository (http://pear.php.net). In case you didn’t know, PEAR is an online repository of free PHP software, including classes and modules for everything from data archiving to XML parsing. This Log class is maintained by Jon Parise, and the latest version can be downloaded from http://pear.php.net/package-info.php?package=Log
[28-Feb-2002 16:15:06] Failed opening ‘common.php’ for inclusion (include_path=’.;’) (error type 2)
Like the error_log() function, the PEAR Log class allows logging to a variety of different destinations – system logger, text file, email address, database and even MCAL. Here’s an example demonstrating basic usage:
The first step here is to include() the Log class:
<?php // include class include(“Log.php”); // create Log object $l = &Log::singleton(“file”, “my.log”); // test it $v = “Mary had a little lamb”; if (!is_numeric($v)) { $l->log(“Non-numeric variable encountered”, PEAR_LOG_WARNING); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { $l->log(“No fish available”, PEAR_LOG_ERR); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { $l->log(“Could not connect to database”, PEAR_LOG_CRIT); } ?>
Once that’s done, a new Log object can be created. This object constructor requires, as its first parameter, a string indicating the kind of log to open – current valid values are ‘console’, ‘syslog’, ‘sql’, ‘file’, and ‘mcal’. Depending on the log type, additional data may be provided – the name of the file to use in case of a file logger, for example.
// include class include(“Log.php”);
The Log class internally defines eight priority levels for logging – here’s the list, culled directly from the source code of the class:
// create Log object $l = &Log::singleton(“file”, “my.log”);
Each log message that you send to the logger can be flagged with a specific priority, and the logger can be set up to log only those messages matching or exceeding a specific priority level (by default, all messages are logged). This can be clearly seen from the test code below, in which each message to the logger includes a priority level:
$priorities = array( PEAR_LOG_EMERG => ‘emergency’, PEAR_LOG_ALERT => ‘alert’, PEAR_LOG_CRIT => ‘critical’, PEAR_LOG_ERR => ‘error’, PEAR_LOG_WARNING => ‘warning’, PEAR_LOG_NOTICE => ‘notice’, PEAR_LOG_INFO => ‘info’, PEAR_LOG_DEBUG => ‘debug’ );
Here’s what the log file looks like:
$v = “Mary had a little lamb”; if (!is_numeric($v)) { $l->log(“Non-numeric variable encountered”, PEAR_LOG_WARNING); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { $l->log(“No fish available”, PEAR_LOG_ERR); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { $l->log(“Could not connect to database”, PEAR_LOG_CRIT); }
If you’d like to tell the logger to only log messages above a certain priority level – for example, critical and above – this priority level should be specified as the fifth argument to the object constructor. Consider the following revision of the previous example:
Nov 26 06:47:15 [warning] Non-numeric variable encountered Nov 26 06:47:15 [error] No fish available Nov 26 06:47:17 [critical] Could not connect to database
In this case, only messages flagged as PEAR_LOG_ERR and above will be written to the specified log file.{mospagebreak title=Destination Unknown} The Log class also supports sending log messages to the console, the system logger, an SQL database or a user-specified email address. Take a look:
<?php // include class include(“Log.php”); // create Log object $l = &Log::singleton(“file”, “my.log”, NULL, array(), PEAR_LOG_ERR); // test it $v = “Mary had a little lamb”; if (!is_numeric($v)) { $l->log(“Non-numeric variable encountered”, PEAR_LOG_WARNING); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { $l->log(“No fish available”, PEAR_LOG_ERR); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { $l->log(“Could not connect to database”, PEAR_LOG_CRIT); } ?>
In this case, log messages are directed to the text console (if you’re running this script via a Web server, the console is the browser window). Here’s the output:
<?php // include class include(“Log.php”); // create Log object $l = &Log::singleton(“console”); // test it $v = “Mary had a little lamb”; if (!is_numeric($v)) { $l->log(“Non-numeric variable encountered”, PEAR_LOG_WARNING); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { $l->log(“No fish available”, PEAR_LOG_ERR); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { $l->log(“Could not connect to database”, PEAR_LOG_CRIT); } ?>
Messages can also be sent to an SQL database,
Nov 26 22:05:25 [warning] Non-numeric variable encountered Nov 26 22:05:25 [error] No fish available Nov 26 22:05:27 [critical] Could not connect to database
which can then be queried to retrieve subsets of the log messages, sorted by date or priority level.
<?php // include class include(“Log.php”); // create Log object // second argument is table name // fourth argument is PHP::DB compatible DSN for database access $l = &Log::singleton(“sql”, “log_table”, “”, array(‘dsn’ => ‘mysql://joe:pass@localhost/test’)); // test it $v = “Mary had a little lamb”; if (!is_numeric($v)) { $l->log(“Non-numeric variable encountered”, PEAR_LOG_WARNING); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { $l->log(“No fish available”, PEAR_LOG_ERR); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { $l->log(“Could not connect to database”, PEAR_LOG_CRIT); } ?>
Finally, log messages can also be directed to a specified email address, as in the following example:
mysql> SELECT * FROM log_table WHERE priority >= 4; +—————-+——-+———-+———————————-+ | logtime | ident | priority | message | +—————-+——-+———-+———————————-+ | 20021126074936 | | 4 | Non-numeric variable encountered | | 20021126074936 | | 4 | Non-numeric variable encountered | | 20021126074937 | | 4 | Non-numeric variable encountered | +—————-+——-+———-+———————————-+ 3 rows in set (0.05 sec)
You can customize the mail message by adding an array containing a custom From: and Subject: line to the object constructor, as below:
<?php // include class include(“Log.php”); // create Log object $l = &Log::singleton(“mail”, “admin@host.com”); // test it $v = “Mary had a little lamb”; if (!is_numeric($v)) { $l->log(“Non-numeric variable encountered”, PEAR_LOG_WARNING); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { $l->log(“No fish available”, PEAR_LOG_ERR); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { $l->log(“Could not connect to database”, PEAR_LOG_CRIT); } ?>
{mospagebreak title=Artificial Intelligence} You can also configure PHP to automatically log all script errors to a specific file via the special “log_errors” configuration directive in “php.ini”. This directive, when set to true, logs all PHP errors to either a user-specified log file (the value of this file must be specified in the “error_log” configuration directive, also set via “php.ini”), or to the Web server error log if no log file is specified.
<?php // include class include(“Log.php”); // create Log object $l = &Log::singleton(“mail”, “admin@host.com”, NULL, array(‘from’ => ‘L. Ogger’, ‘subject’ => ‘Log message’)); // test it $v = “Mary had a little lamb”; if (!is_numeric($v)) { $l->log(“Non-numeric variable encountered”, PEAR_LOG_WARNING); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { $l->log(“No fish available”, PEAR_LOG_ERR); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { $l->log(“Could not connect to database”, PEAR_LOG_CRIT); } ?>
Consider the following example, which demonstrates:
In this case, I’m manually instantiating an error by attempting to include a file which does not exist. Obviously, PHP will barf and display an error screen containing the following:
<?php // turn on automatic error logging ini_set(‘log_errors’, true); // include non-existent file include(“non.existent.file.php”); ?>
The same error also appears in the server’s error log:
Warning: Failed opening ‘non.existent.file.php’ for inclusion (include_path=’.;/usr/local/php/includes’) in error.php on line 10
You can turn off PHP error display, and only have the error message appear in the log file, by setting the “display_errors” variable (also accessible via “php.ini”) to false. Consider the following variant of the previous example, which demonstrates:
[Tue Nov 26 12:49:31 2002] [error] PHP Warning: Failed opening ‘non.existent.file.php’ for inclusion (include_path=’.;/usr/local/php/includes’) in error.php on line 10
In this case, though an error takes place, it is never displayed to the user, but merely gets logged to the server’s error log.
<?php // turn on automatic error logging ini_set(‘log_errors’, true); // turn off error display ini_set(‘display_errors’, false); // include non-existent file include(“non.existent.file.php”); ?>
On *NIX systems, setting the “error_log” variable to the special value “syslog” logs all errors via the standard “syslog” daemon.{mospagebreak title=Big Brother Is Watching} Finally, let’s wrap things up with a couple of examples that show how the various techniques demonstrated above can be used to build logs and audit trails for a Web application.
In the first example, every time a Web page is displayed, a log entry is made in an “access.log” file. This log entry is a comma-separated list of values containing the URL requested, the client browser identification string, and a timestamp.
Here’s a snippet from the access log:
<?php // create log string $str = date(“Y/m/d h:i:s”, mktime()) . “,” . $_SERVER['REQUEST_URI'] . “,” . $_SERVER['HTTP_USER_AGENT'] . “n”; // write to file error_log($str, 3, “access.log”); // rest of page here ?>
Since this data is in a structured format, it can easily be analyzed and a “hit count” created for each URL in the file. This next script does exactly that:
2002/11/26 09:07:38,/alpha.php,Mozilla/4.0 (compatible; MSIE 5.0; Windows 95) 2002/11/26 09:07:38,/alpha.php,Mozilla/4.0 (compatible; MSIE 5.0; Windows 95) 2002/11/26 09:10:31,/home/hello.php,Mozilla/4.0 (compatible; MSIE 5.0; Windows 95) 2002/11/26 09:17:38,/index.php,Mozilla/4.0 (compatible; MSIE 5.0; Windows 95) 2002/11/26 09:17:38,/base/index.php,Mozilla/4.0 (compatible; MSIE 5.0; Windows 95)
This script parses the “access.log” file, and creates a PHP associative array whose keys correspond to the URLs found in the file. The value associated with each key is an integer indicating the number of appearances the URL makes in the file. Once the entire file has been parsed, the $urlStats array contains a list of all the unique URLs in the access log, together with the number of times each has appeared. This data can then be used to generate a report of the most frequently-accessed URLs.
<?php // create array to hold unique URLs $urlStats = array(); // read access log $lines = file(“access.log”); // iterate through access log foreach ($lines as $l) { $data = explode(“,”, $l); $ts = $data[0]; $url = $data[1]; $agent = $data[2]; // check to see if URL exists in array // if it does, increment incidence count // if it does not, create a new key with incidence count 1 if ($urlStats[$url]) { $urlStats[$url]++; } else { $urlStats[$url] = 1; } } // print list of unique URLs with count print_r($urlStats); ?>
Consider this next example, which provides an API for adding, editing and deleting users to (from) a Web application. Each time the user database is edited, a separate audit() process tracks the change, logging both the nature of the change and information about the user initiating the change. This log data is stored in a separate SQL table, from where it can be retrieved for statistical reporting, user activity monitoring or debugging.
Here’s a snippet from the audit table:
<?php // assume that administrator has logged in to system to perform user-administration tasks // admin username is stored in a session variable by default // this is useful for audit purposes session_start(); $_SESSION['LOGGED_IN_USER'] = “john”; // add a new user function addUser($user, $pass, $perms) { // open connection to database $connection = mysql_connect(“localhost”, “joe”, “pass”) or die (“Unable to connect!”); mysql_select_db(“myapp”) or die (“Unable to select database!”); // formulate and execute query $query = “INSERT INTO users (user, pass, perms) VALUES(‘$user’, ‘$pass’, ‘$perms’)”; mysql_query($query) or die (“Error in query: $query. ” . mysql_error()); // log activity to audit database audit(“ADD_USER”, $_SESSION['LOGGED_IN_USER'], “$user:$pass:$perms”, addslashes($query)); // close connection mysql_close($connection); } // edit an existing user function updateUser($user, $pass, $perms) { $connection = mysql_connect(“localhost”, “joe”, “pass”) or die (“Unable to connect!”); mysql_select_db(“myapp”) or die (“Unable to select database!”); // formulate and execute query $query = “UPDATE users SET pass = ‘$pass’, perms = ‘$perms’ WHERE user = ‘$user’”; mysql_query($query) or die (“Error in query: $query. ” . mysql_error()); // log activity to audit database audit(“UPDATE_USER”, $_SESSION['LOGGED_IN_USER'], “$user:$pass:$perms”, addslashes($query)); // close connection mysql_close($connection); } // delete an existing user function deleteUser($user) { $connection = mysql_connect(“localhost”, “joe”, “pass”) or die (“Unable to connect!”); mysql_select_db(“myapp”) or die (“Unable to select database!”); // formulate and execute query $query = “DELETE FROM users WHERE user = ‘$user’”; mysql_query($query) or die (“Error in query: $query. ” . mysql_error()); // log activity to audit database audit(“DELETE_USER”, $_SESSION['LOGGED_IN_USER'], “$user”, addslashes($query)); // close connection mysql_close($connection); } // generic audit function // logs all activity to a database function audit($op, $owner, $args, $msg) { $connection = mysql_connect(“localhost”, “root”, “pass”) or die (“Unable to connect!”); mysql_select_db(“trails”) or die (“Unable to select database!”); // formulate and execute query $query = “INSERT INTO audit (timestamp, op, owner, args, msg) VALUES (NOW(), ‘$op’, ‘$owner’, ‘$args’, ‘$msg’)”; mysql_query($query) or die (“Error in query: $query. ” . mysql_error()); } addUser(“joe”, “joe”, 3); addUser(“sarahh”, “bsdfg49″, 1); updateUser(“joe”, “joe”, 4); deleteUser(“sarahh”); addUser(“sarah”, “bsdfg49″, 1); ?>
This audit table can then be queried to obtain detailed information on the activities performed by the various users, sorted by time or type of activity. For example,
+———————+————-+——-+ | timestamp | op | owner | +———————+————-+——-+ | 2002-11-26 08:28:05 | UPDATE_USER | john | | 2002-11-26 08:28:05 | DELETE_USER | john | | 2002-11-26 08:28:05 | ADD_USER | john | | 2002-11-26 08:33:14 | ADD_USER | joe | +———————+————-+——-+
This is a somewhat trivial example, but it serves to demonstrate the concept of logging activity and using those logs to build an audit trail. While you can make this as complex as you want, tracking everything from user clicks to form input in order to gain a better understanding of how users navigate through and use your application, remember that every addition to the log affects the overall performance of your application; log too much data and your application will suffocate and die.{mospagebreak title=Closing Time} And that’s about it for the moment. In this article, I offered you a brief overview of logging in PHP, demonstrating how you can use built-in functions, off-the-shelf libraries or your own code to easily and efficiently create logs of the activity taking place in your application. I demonstrated logging to a file, to a database, to an email address and to the console, and wrapped things up with a couple of simple examples that demonstrated how logs could be built and analyzed in a real-world application.
mysql> SELECT timestamp, op, args FROM trails WHERE timestamp >= mysql> 2002-11-26 AND owner = ‘joe’; +———————+————-+——————+ | timestamp | op | args | +———————+————-+——————+ | 2002-11-26 08:33:29 | ADD_USER | joe:joe:3 | | 2002-11-26 08:33:29 | ADD_USER | sarahh:bsdfg49:1 | | 2002-11-26 08:33:29 | UPDATE_USER | joe:joe:4 | | 2002-11-26 08:33:29 | DELETE_USER | sarahh | | 2002-11-26 08:33:29 | ADD_USER | sarah:bsdfg49:1 | +———————+————-+——————+
I hope you enjoyed reading this article as much as I enjoyed writing it. If you’d like to know more about the topics discussed in the previous pages, here are some links you should bookmark:
PHP file manipulation functions, at http://www.php.net/manual/en/ref.filesystem.php
PHP mail functions, at http://www.php.net/manual/en/ref.mail.php
PHP MySQL functions, at http://www.php.net/manual/en/ref.mysql.php
PHP error logging functions, at http://www.php.net/manual/en/ref.errorfunc.php
The PHP Log class, at http://pear.php.net/package-info.php?package=Log
PEAR, at http://pear.php.net
Till next time…stay healthy!
Note: All examples in this article have been tested on Linux/i586 with PHP 4.2.3. Examples are illustrative only, and are not meant for a production environment. Melonfire provides no warranties or support for the source code described in this article. YMMV!
Related Threads
Related Articles
訂閱:
文章 (Atom)