日志是一个项目中非常重要的部分,用来做分析最合适了,下面呢咱们就模仿 php fpm的方式,在swoole的http中写一个系统日志的写入功能。
class HttpServer
{
const HOST = '0.0.0.0';
const PROT = '9510';
public $http = null;
public function __construct()
{
$this->http = new swoole\http\server(self::HOST, self::PROT);
$this->http->set([
'worker_num' => 8,
'task_worker_num' => 2,
// 开启静态文件请求
'enable_static_handler' => true,
// 配置静态文件根目录
'document_root' => '/www/wwwroot/swoole_gyy/thinkphp/public/static',
]);
$this->http->on('workerStart', [$this, 'onWorkerStart']);
$this->http->on('request', [$this, 'onRequest']);
$this->http->start();
}
/**
* 监听客户端的请求响应
* 在本方法中加入记录日志的代码
* @param $request
* @param $response
*/
public function onRequest($request, $response)
{
if ($request->server['request_uri'] == '/favicon.ico') {
$response->end();
return;
}
// 转换 request
self::transition($request);
// 写入日志
self::writeLog();
// 将httpServer 放到$_POST超全局变量中,方便其他页面使用
$_POST['http_server'] = $this->http;
ob_start();
try {
// 2. 执行应用
think\App::run()->send();
} catch (\Exception $e) {
var_dump([
'file' => $e->getFile(),
'line' => $e->getLine(),
'errmsg' => $e->getMessage()
]);
}
$res = ob_get_contents();
ob_end_clean();
// 发送消息到客户端
$response->end($res);
}
/**
* 转换 request
* @param $request
*/
private static function transition($request)
{
$_SERVER = [];
$_GET = [];
$_POST = [];
if (isset($request->server)) {
foreach ($request->server as $k => $v) {
$_SERVER[strtoupper($k)] = $v;
}
}
if (isset($request->header)) {
foreach ($request->header as $k => $v) {
$_SERVER[strtoupper($k)] = $v;
}
}
if (isset($request->get)) {
foreach ($request->get as $k => $v) {
$_GET[$k] = $v;
}
}
if (isset($request->post)) {
foreach ($request->post as $k => $v) {
$_POST[$k] = $v;
}
}
}
/**
* 写入日志
*/
private static function writeLog()
{
$data = array_merge(['date' => date('Ymd H:i:s')], $_GET, $_POST, $_SERVER);
$logs = '';
foreach ($data as $key => $val) {
$logs .= $key. ':'. $val. ' --- ';
}
$logPath = APP_PATH."../runtime/log/". date('Ym'). '/'. date('d'). '_access.log';
// 通过协程的方法写入日志
go(function() use ($logPath, $logs){
file_put_contents($logPath, $logs. PHP_EOL, FILE_APPEND);
});
}
}
new HttpServer;
注:每次http请求,都会执行 onRequest 方法,日志都会记录下来。