发布于 5年前

Laravel如何将日志分类保存

添加到你的helpers.php文件

/**
 * 封装写入日志
 *
 * @param  string $message //信息
 * @param  array $content //数组内容,比如调用栈
 * @param  string $sub_path//保存文件夹名
 * @param  string $level//错误级别
 * @return void
 */
if (!function_exists("save_log")) {
    function save_log($message, $content = [], $sub_path = '', $level = 'info')
    {
        try {
            $day = date('Y-m-d');
            $path = config('global.log_save_path');

            if (!empty($sub_path)) {
                $path .= "/{$sub_path}";
                if (!is_dir($path)) {
                    mkdir($path, 0777, true);
                }
            }

            $path .= "/{$day}.log";//每天都有一个日志文件

            $logger = \Illuminate\Support\Facades\Log::getMonolog();

            $handlers = $logger->getHandlers();
            $needToAddHandler = true;

            foreach ($handlers as $handler) {
                if ($handler->getUrl() == $path) {
                    $needToAddHandler = false;
                }
            }

            if ($needToAddHandler) {
                $logger->pushHandler(new \Monolog\Handler\StreamHandler($path, $level));
            }

            $logger->log($level, $message, $content);
        } catch (ErrorException $err) {
            echo $err->getMessage();
        }
    }
}
©2020 edoou.com   京ICP备16001874号-3