Laravel 指定日志文件记录任意日志

方法一:

use Monolog\Logger;

(new Logger('local'))
            ->pushHandler(new RotatingFileHandler(storage_path('logs/api.log')))
            ->info("test", ['data' => "zxc", 'error' => 'error']);

方法二:

Log::useFiles(storage_path('logs/api.log'), 'debug');
Log::debug("test --------------------------------");

方法三:

<?php
namespace App\Library;

use Illuminate\Log\Writer;
use Monolog\Logger;

/**
 * 自定义日志类实现
 * Class BLogger
 * @package App\Library
 */
class BLogger
{
// 所有的LOG都要求在这里注册
    const LOG_ERROR = 'error';
    const LOG_DEBUG = 'debug';
    const LOG_INFO = 'info';

    private static $loggers = [];

    // 获取一个实例
    public static function getLogger($type = self::LOG_ERROR, $day = 30)
    {
        if (empty(self::$loggers[$type])) {
            self::$loggers[$type] = new Writer(new Logger($type));
            self::$loggers[$type]->useDailyFiles(storage_path() . '/logs/' . $type . '.log', $day);
        }

        $log = self::$loggers[$type];
        return $log;
    }
}

具体使用:

BLogger::getLogger(BLogger::LOG_ERROR)->error('test', ['test' => 'zxc']);

在 storage/logs/error_xxxx-xx-xx.log 查看文件内容

总结:
其实方法二和三基本相同。方法三做了个分类.

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 1

还有一种方法,修改 logging.php 这个配置文件,新增下面部分内容,仅供参考

 'channels' => [
       ...
        'file_download' => [
            'driver' => 'daily',
            'path'   => storage_path('logs/file_download/file_download_job.log'),
            'level'  => 'debug',
        ],
    ],

记录日志

Log::channel('file_download')->info('信息', ['xx' => 'xx']);
Log::channel('file_download')->debug('信息', ['xx' => 'xx']);
...

日志文件

file

4年前 评论
sreio 4年前
frans (楼主) 4年前
小李世界 4年前
frans (楼主) 4年前
小李世界 4年前
frans (楼主) 4年前
alvin_cn 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!