webman:全局中间件:记录访问日志(v1.5.7)
一,官方文档地址:
https://www.workerman.net/doc/webman/middleware.html
二,php代码
1,配置中间件:
config/middleware.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<?php /** * This file is part of webman. * * Licensed under The MIT License * For full copyright and license information, please see the MIT-LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @author walkor<walkor@workerman.net> * @copyright walkor<walkor@workerman.net> * @link http://www.workerman.net/ * @license http://www.opensource.org/licenses/mit-license.php MIT License */ return [ '' => [ app\middleware\HttpLog:: class , ] ]; |
2,中间件:
app/middleware/HttpLog.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
<?php namespace app\middleware; use Webman\MiddlewareInterface; use Webman\Http\Response; use Webman\Http\Request; use support\Log; class HttpLog implements MiddlewareInterface { public function process(Request $request , callable $handler ) : Response { echo '这里是请求穿越阶段,也就是请求处理前' ; //开始时间 $startTime = microtime(true); $response = $handler ( $request ); // 继续向洋葱芯穿越,直至执行控制器得到响应 echo '这里是响应穿出阶段,也就是请求处理后' ; //响应时间 $endTime = microtime(true); //共计用时 $costTime = $endTime - $startTime ; //写访问日志,指定通道 //47.92.78.77 - - [20/Aug/2023:02:08:45 +0800] "GET / HTTP/1.1" 200 13364 "-" "Apache-HttpClient/5.1.3 (Java/1.8.0_342)" $log = Log::channel( 'httpLog' ); $ip = $request ->getRemoteIp(); //ip $time = date ( "Y-m-d H:i:s" ); //访问时间 $method = $request ->method(); //method $url = $request ->fullUrl(); //url $version = $request ->protocolVersion(); //http的版本 $status = $response ->getStatusCode(); //返回时的状态码 $size = strlen ( $response ->rawBody()); //内容大小 $agent = $request ->header( 'user-agent' ); //ua //写日志 $content = $ip . " " . $time . " " . $method . " " . $url . " " . $version . " " . $status . " " . $size . " " . $costTime . " " . $agent ; $log ->info( $content ); return $response ; } } |
说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/08/21/webman-quan-ju-zhong-jian-jian-ji-lu-fang-wen-ri-zhi-v1-5-7/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
三,测试效果:
查看日志文件中的记录:
[2023-08-20 22:09:07] httpLog.INFO: 192.168.219.1 2023-08-20 22:09:07 GET //192.168.219.6:8787/image/list 1.1 200 1328 0.0021569728851318 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 [] []
四,查看webman版本:
liuhongdi@lhdpc:/data/webman/imageadmin$ composer show workerman/webman-framework
name : workerman/webman-framework
descrip. : High performance HTTP Service Framework.
keywords : High Performance, http service
versions : * v1.5.7
...