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

文章介绍了一种日志实现方法,通过在程序启动时注册一个挂钟实例,动态记录代码执行时间,当超过预设阈值时记录为慢日志。挂钟类包含构造函数、延迟计算、日志记录和慢日志检测功能。此外,还提到了对SQL查询执行时间的监听来进一步优化性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

在程序 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 保存着查询执行的时间
}
在Python中实现一个简单的圆形挂钟显示功能,我们可以利用Turtle模块来创建图形,并结合time模块获取当前时间。以下是简单的步骤: 首先,确保已经安装了`turtle`库,如果没有,可以使用`pip install turtle`命令安装。 ```python import turtle import time # 创建画布和Turtle实例 window = turtle.Screen() clock_turtle = turtle.Turtle() clock_turtle.speed(0) # 设置绘制速度最快 # 定义时钟形状函数 def draw_clock(radius): clock_turtle.penup() clock_turtle.goto(-radius, -radius) clock_turtle.pendown() clock_turtle.circle(radius) # 更新时间显示 def update_time(): current_hour = int(time.strftime('%I', time.localtime())) if current_hour == 12: hour_digit = '12' else: hour_digit = str(current_hour) minutes = int(time.strftime('%M', time.localtime())) clock_turtle.clear() # 清除上一轮绘制 clock_turtle.color('white') # 设置字体颜色 clock_turtle.fillcolor('black') # 设置填充色 draw_clock(40) # 绘制大圆圈作为表盘背景 draw_clock(35, 'gray') # 细线条表示小时刻度 for i in range(12): # 绘制数字 angle = (i + 1) * 30 # 计算每个数字的角度 clock_turtle.penup() clock_turtle.goto(-45, 45 * math.cos(math.radians(angle))) clock_turtle.write(f'{hour_digit}', font=('Arial', 18, 'normal')) # 写分钟 minute_angle = minutes % 60 * 6 clock_turtle.penup() clock_turtle.goto(-45, 45 * math.cos(math.radians(minute_angle))) clock_turtle.write(f'{minutes}', font=('Arial', 12, 'normal')) # 开始更新并保持窗口打开 while True: update_time() window.update() time.sleep(1) # 每秒更新一次时间 # 最后记得关闭窗口 turtle.done()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值