larave6 简单实现定时监控nginx日志文件功能示例

PHP简单实现定时监控nginx日志文件功能示例

<?php

namespace App\Repositories;

use Illuminate\Support\Facades\Redis;

class LogRepository extends BaseRepository
{
    public $logNameArr  = ''; //读取的日志文件列表
    public $logName     = ''; //读取的日志文件
    public $notifyUrl   = ''; //企微机器人通知地址
    public $size        = '2000'; //分页数据大小
    public $redisPrefix = 'LogController:getFilesize5'; //redis前缀,每个文件re对应不同的key!!!

    function __construct()
    {
        $this->logNameArr = [
            storage_path() . '/logs/laravel-' . date('Y-m-d') . '.log',//日志路径
        ];
    }

    /**
     * 将错误日志通知到微信
     */
    public function handle()
    {
        if (!empty($this->logNameArr)) {
            foreach ($this->logNameArr as $logName) {
                $this->logName = $logName;
                if (!file_exists($this->logName)) {
                    continue;
                }
                try {
                    $logSize = $this->getFilesize();
                    //运行时log文件原始大小
                    if (empty($logSize)) {//没有记录上次位置,则从初始位置开始
                        $file_size = 0;
                    } else { //从上次记录的位置开始
                        $file_size = $logSize;
                    }
                    $fp = fopen($this->logName, "r");
                    $n  = 1;
                    while ($n < 2) {
                        clearstatcache();
                        $file_size_new = filesize($this->logName);
                        $add_size      = $file_size_new - $file_size;
                        $add_log       = '';
                        if ($add_size > 0) {
                            fseek($fp, $file_size);
                            //当增加量超过8192,需要分页读取增加量
                            $page = ceil($add_size / $this->size);
                            for ($i = 1; $i <= $page; $i++) {
                                if ($i == $page) {//最后一页
                                    $end_add = $add_size - ($page - 1) * $this->size;
                                    $add_log = fread($fp, $end_add);
                                } else {
                                    $add_log        = fread($fp, $this->size);
                                    $file_size_step = $file_size + $i * $this->size;
                                    fseek($fp, $file_size_step);
                                }
                                sleep(1);
                                $this->sendWeiXin($add_log);
                            }

                            $file_size = $file_size_new;
                            //记录当前位置
                            $this->saveFilesize($file_size);
                        }
                        $n++;
                    }
                    fclose($fp);
                } catch (\Exception $e) {
                    var_dump($e->getMessage());;
                }
            }
        }

        echo 'LogRepository done';
        exit();
    }

    /**
     * 每次启动时获取上次打开文件位置
     */

    public function getFilesize()
    {
        $size = redis::get($this->redisPrefix . $this->logName);
        return $size ?: 0;
    }

    /**
     * 每次提交后保存这次读取文件的位置
     */
    public function saveFilesize($size)
    {
        return redis::setex($this->redisPrefix . $this->logName, 86400, $size);
    }

    public function sendWeiXin($content)
    {
        $app = env('APP_ENV', '');
        if ($app == 'master') {
            $title = '正式环境告警:' . PHP_EOL;
        } else if ($app == 'dev') {
            $title = '测试环境告警:' . PHP_EOL;
        }
        $data          = [
            'msgtype' => 'text',
            'text'    => [
                'content' => $title . '日志路径' . $this->logName . PHP_EOL . $content,
            ],
        ];
        $return_header = ["Content-Type: application/json"];
        $data          = json_encode($data);
        $res           = $this->httpPost($this->notifyUrl, $data, $return_header);
        return $res;
    }

    /**
     * http请求
     *
     * @param  array  $data
     *
     * @return boolean
     */

    public function httpPost($url = '', $data = [], $header)
    {
        if (empty($url)) {
            return FALSE;
        }
        if ($data) {
            //$data = http_build_query($data);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }

        $return = curl_exec($ch);
        curl_close($ch);
        return $return;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值