vr-shopxo-source/thinkphp/library/think/Log.php

388 lines
8.8 KiB
PHP
Executable File

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think;
class Log implements LoggerInterface
{
const EMERGENCY = 'emergency';
const ALERT = 'alert';
const CRITICAL = 'critical';
const ERROR = 'error';
const WARNING = 'warning';
const NOTICE = 'notice';
const INFO = 'info';
const DEBUG = 'debug';
const SQL = 'sql';
/**
* 日志信息
* @var array
*/
protected $log = [];
/**
* 配置参数
* @var array
*/
protected $config = [];
/**
* 日志写入驱动
* @var object
*/
protected $driver;
/**
* 日志授权key
* @var string
*/
protected $key;
/**
* 是否允许日志写入
* @var bool
*/
protected $allowWrite = true;
/**
* 应用对象
* @var App
*/
protected $app;
public function __construct(App $app)
{
$this->app = $app;
}
public static function __make(App $app, Config $config)
{
return (new static($app))->init($config->pull('log'));
}
/**
* 日志初始化
* @access public
* @param array $config
* @return $this
*/
public function init($config = [])
{
$type = isset($config['type']) ? $config['type'] : 'File';
$this->config = $config;
unset($config['type']);
if (!empty($config['close'])) {
$this->allowWrite = false;
}
$this->driver = Loader::factory($type, '\\think\\log\\driver\\', $config);
return $this;
}
/**
* 获取日志信息
* @access public
* @param string $type 信息类型
* @return array
*/
public function getLog($type = '')
{
return $type ? $this->log[$type] : $this->log;
}
/**
* 记录日志信息
* @access public
* @param mixed $msg 日志信息
* @param string $type 日志级别
* @param array $context 替换内容
* @return $this
*/
public function record($msg, $type = 'info', array $context = [])
{
if (!$this->allowWrite) {
return;
}
if (is_string($msg) && !empty($context)) {
$replace = [];
foreach ($context as $key => $val) {
$replace['{' . $key . '}'] = $val;
}
$msg = strtr($msg, $replace);
}
if (PHP_SAPI == 'cli') {
// 命令行日志实时写入
$this->write($msg, $type, true);
} else {
$this->log[$type][] = $msg;
}
return $this;
}
/**
* 清空日志信息
* @access public
* @return $this
*/
public function clear()
{
$this->log = [];
return $this;