<?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' );