记录一个比较好的日志实现方式“挂钟实例”

看到个比较好的日志实现方式,记录一下。

在程序 boot 的时候挂一个钟表实例注册到 app 中,每隔一段代码就去问一下他,到目前为止过了多久了,并写到日志中。

以下是挂钟的实现:class WallTime
{
    /**
     * 默认标记长度
     */
    const MARK_LENGTH_DEFAULT       = 6;

    /**
     * 慢日志默认超时时间
     */
    const SLOW_LOG_TIMEOUT_DEFAULT  = 3;

    /**
     * @var float 挂钟时间
     */
    protected $wallTime;

    /**
     * @var string 标识
     */
    protected $mark;

    /**
     * @var array 日志数据
     */
    protected $log  = [];

    /**
     * 构造函数
     *
     * @param int $markLength
     */
    public function __construct(int $markLength = self::MARK_LENGTH_DEFAULT)
    {
        $this->wallTime = microtime(true);
        $this->mark     = Str::random($markLength);
    }

    /**
     * 经过时间
     *
     * @return float
     */
    public function delay(): float
    {
       return   round(microtime(true)-$this->wallTime,2);
    }

    /**
     * 获取标识
     *
     * @return string
     */
    public function mark(): string
    {
        return $this->mark;
    }

    /**
     * 记录日志
     *
     * @param array $data
     */
    public function info(array $data = [])
    {
        info($this->message(), $data);
    }

    /**
     * 慢日志
     *
     * @param array $data
     * @param int $timeout
     */
    public function slow(array $data = [], int $timeout = self::SLOW_LOG_TIMEOUT_DEFAULT)
    {
        $this->log[]    = [
            $this->message(),
            $data,
        ];

        if ($this->delay() > $timeout) {
            foreach ($this->log as $item) {
                info($item[0],$item[1]);
            }
            $this->log  = [];
        }
    }

    /**
     * 消息体
     *
     * @return string
     */
    protected function message(): string
    {
        $delay  = $this->delay();

        return  "$this->mark\t$delay";
    }
}Copy

然后通过 AppServiceProvider 注册到 app 中

        $this->app->instance('wallTime', new WallTime());
        // 以下是给队列任务加的挂钟,用不到可以不加
        Queue::before(function (JobProcessing $event) {
            $this->app->instance('wallTime', new WallTime());
        });

定位程序中执行缓慢的位置

resolve('wallTime')->slow([__FILE__, __LINE__]);

SQL 日志则可以添加查询事件的监听器:

public function handle(QueryExecuted $event)
{
    // 监听查询执行事件,里面 $event->time 保存着查询执行的时间
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值