网站首页文章详情

Laravel 中自定义日志目录

发布时间:2019-07-05 10:34编辑:胜男

https://learnku.com/articles/7125/custom-log-directory-in-laravel


通过以上思路自己写了个公共类如下

<?php
// +----------------------------------------------------------------------
// | Laravel
// +----------------------------------------------------------------------
// | Copyright (c) 2014~2020 http://ganhuoche.com All rights reserved.
// +----------------------------------------------------------------------
// | Author     : zuopeng <zuopeng@ganhuoche.com>
// +----------------------------------------------------------------------
// | CreateTime : 2019/7/5 10:46 
// +----------------------------------------------------------------------
// | 使用方式:LogCommon::info('info'); or LogCommon::init(['dir'=>'dir'])->info('info');
// +----------------------------------------------------------------------


namespace App\Services\Admin\Common;


class LogCommon
{
    //根目录
    protected static $pathRoot  = 'logs/';
    //默认目录
    protected static $path      = 'admin/';
    //自定义文件夹
    protected static $dir       = '';

    /**
     * @param array $param
     * @return LogCommon
     */
    public static function init($param = []){
        if(isset($param['path'])){
            self::$path = $param['path'];
        }
        if(isset($param['dir'])){
            self::$dir = $param['dir'];
        }

        return new self();
    }

    private static function initLog(){
        $monolog = \Log::getMonolog();
        $monolog->popHandler();
        \Log::useDailyFiles(storage_path(self::$pathRoot.self::$path.self::$dir.'info.log'));
    }

    public static function info($str=''){
       self::initLog();
        \Log::info($str);
    }

    public static function error($str=''){
        self::initLog();
        \Log::error($str);
    }

    /**
     * @param string $dir
     */
    public static function setDir(string $dir)
    {
        self::$dir = $dir;
    }

    /**
     * @param string $path
     */
    public static function setPath(string $path)
    {
        self::$path = $path;
    }

}