接上一篇文章,日志文件的写入和存储搞定了,下面开始写记录方法
日志主要记录了事件,报错类型,异常类型,类,进程id,日志级别等,参考了Monolog的写法。
<?php
namespace App\Http\Utils;
class Logger
{
/**
* Detailed debug information
*/
public const DEBUG = 100;
/**
* Interesting events
*
* Examples: User logs in, SQL logs.
*/
public const INFO = 200;
/**
* Uncommon events
*/
public const NOTICE = 250;
/**
* Exceptional occurrences that are not errors
*
* Examples: Use of deprecated APIs, poor use of an API,
* undesirable things that are not necessarily wrong.
*/
public const WARNING = 300;
/**
* Runtime errors
*/
public const ERROR = 400;
/**
* This is a static variable and not a constant to serve as an extension point for custom levels
*
* @var string[] $levels Logging levels with the levels as key
*/
protected static $levels = [
self::DEBUG => 'DEBUG',
self::INFO => 'INFO',
self::NOTICE => 'NOTICE',
self::WARNING => 'WARNING',
self::ERROR => 'ERROR'
];
public static function log($output,$type = 400)
{
$data = [
"@timestamp" => date(DATE_ISO8601),//格式化为ISO8601
"hostname"=>gethostname(), //主机名称,系统变量获取
"app_name"=>"test-api", //应用名称,
"level"=> self::$levels[$type], // 日志级别: debug info warn error
"msg"=> $output['msg'], // 日志信息:
"thread"=> getmypid(), // 进程id,线程名称
"class"=> $output['class'], // 应用类名
"execption"=>$output['exception'], // 异常信息
];
file_put_contents('/logs/test'.date('Y-m-d').'.log',json_encode($data).PHP_EOL,FILE_APPEND);
return true;
}
}
调用:
public function demo(){
$output = [
'class' => __CLASS__,
'msg' => 'service error',
'exception' => 'error error error'
];
Logger::log($output,400);
}
一个简单的日志类就完成了,临时先用着,后面肯定还是要上云。
网友评论