*PHPのログ処理 [#p043d596]
インスタンスを作るのは面倒。普通の関数の方が楽でいい。というコンセプト。
<?php
function _log($type,$mesg,$d,$opt){
$line = $d['line'];
$file = str_replace(BASE_PATH,'',$d['file']);
$date = date('y-m-d H:i');
if ($opt){
$type = $opt;
}
$mesgs = array();
if (is_array($mesg) || is_object($mesg)){
$mesgs = split("\n",trim(print_r($mesg,true)));
}else{
$mesgs[] = $mesg;
}
foreach ($mesgs as $mesg){
error_log(sprintf("%- 5s [ %s ][ %s:%d ] %s",
$type,
$date,
$file,$line,
$mesg));
}
}
function debug($mesg,$opt=null) {
if ($ERROR_LEVELS['debug'] >= ERROR_LEVEL){
list($d) = debug_backtrace();
_log('DEBUG',$mesg,$d,$opt);
}
}
function warn($mesg,$opt=null) {
if ($ERROR_LEVELS['warn'] >= ERROR_LEVEL){
list($d) = debug_backtrace();
_log('WARN',$mesg,$d,$opt);
}
}
function fatal($mesg,$opt=null) {
if ($ERROR_LEVELS['fatal'] >= ERROR_LEVEL){
list($d) = debug_backtrace();
_log('FATAL',$mesg,$d,$opt);
}
}
// エラーレベルリストの定義
$ERROR_LEVELS = array(
'debug' => 0,
'warn' => 1,
'fatal' => 2
);
?>
** 使い方 [#a5bf9e83]
// エラーレベルの定義(運用時は高く、開発時は低く)
define('ERROR_LEVEL',0);
// アプリケーションのベースパス
define('BASE_PATH','/home/ryuichi');
debug(1);
dummy();
fatal(array(1,2,3));
function dummy() {
warn(1,__FUNCTION__);
}
** 実行結果 [#j0c7fa8b]
DEBUG [ 06-04-14 16:33 ][ /tmp2/test.php:54 ] 1
dummy [ 06-04-14 16:33 ][ /tmp2/test.php:59 ] 1
FATAL [ 06-04-14 16:33 ][ /tmp2/test.php:56 ] Array
FATAL [ 06-04-14 16:33 ][ /tmp2/test.php:56 ] (
FATAL [ 06-04-14 16:33 ][ /tmp2/test.php:56 ] [0] => 1
FATAL [ 06-04-14 16:33 ][ /tmp2/test.php:56 ] [1] => 2
FATAL [ 06-04-14 16:33 ][ /tmp2/test.php:56 ] [2] => 3
FATAL [ 06-04-14 16:33 ][ /tmp2/test.php:56 ] )