1. 程式人生 > >專案記錄日誌類

專案記錄日誌類

<?php

class Logger

{

private static function createdir($dir){

//檢查目錄或檔案是否存在

if(file_exists($dir))return true;

//把\替換為/

$dir = str_replace("\\","/",$dir);

substr($dir,-1)=="/"?$dir=substr($dir,0,-1):"";

$dir_arr = explode("/",$dir);

$str = '';

foreach($dir_arr as $k=>$a){

$str = $str.$a."/";

if(!$str)continue;

if(!file_exists($str))mkdir($str,0775);

}

return true;

}

 

private static function log( $filepath, $line ){

//建立目錄

self::createdir(dirname($filepath));

$line = date("Y-m-d H:i:s").'=>'.$line;

file_put_contents($filepath, $line."\n", FILE_APPEND);

}

/**

* 紀錄錯誤日誌

*/

public static function errorLog( $content , $type='log', $filename='open' ){

$filepath = \Yii::$app->basePath. '/log/' . $filename . date('/Y/m/d/') . $type . '.txt';

self::log( $filepath , $content );

}

/**

* 紀錄錯誤日誌

* 按月分組

*/

private static function saveLog( $categore , $content ,$suffix = 'txt'){

$filepath =__DIR__."/log/{$categore}/" . date('Ym/d') . '.'.$suffix;

self::log( $filepath , $content );

}

/**

* 日誌記法

* 0: file

* 1... 內容自動以\t分隔, 陣列自動var_export($c,true)轉換成串

*/

public static function dayLog(){

//1 獲取第一個引數作為檔名

$params = func_get_args();

$filePath = $params[0];

if( !$filePath ){

return false;

}

unset($params[0]);

if(empty($params)){

return false;

}

 

//2 將引數重組

$ps = [];

foreach($params as $param){

if( is_array($param) || is_object($param) ){

$param = var_export($param, true);

}

$ps[] = $param;

}

 

$content = implode("\t:\t", $ps);

static::saveLog($filePath, $content);

return true;

}

/**

* 日誌記法

* 0: file

* 1... 內容自動以\t分隔, 陣列自動var_export($c,true)轉換成串

*/

public static function dayLogCsv(){

//1 獲取第一個引數作為檔名

$params = func_get_args();

$filePath = $params[0];

if( !$filePath ){

return false;

}

unset($params[0]);

if(empty($params)){

return false;

}

 

//2 將引數重組

$ps = [];

foreach($params[1] as $key => $param){

if( is_array($param) || is_object($param) ){

$param = var_export($param, true);

}

$ps[$key] = $param;

}

 

$content = implode(",", $ps);

static::saveLog($filePath, ','.$content,'csv');

return true;

}

}

 

$oLogger = new Logger();

$oLogger::dayLog('study','a=>我是a','b=>我是b','c','d','e');