Skip to content

Commit

Permalink
improve logger (#113)
Browse files Browse the repository at this point in the history
  • Loading branch information
宋神宗 authored Mar 27, 2019
1 parent 2b9d2f0 commit c8405ac
Show file tree
Hide file tree
Showing 9 changed files with 150 additions and 13 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# CHANGELOG

## 1.0.26 - 2019-03-27
- Support `pid`, `cost`, `start_time` for Log.


## 1.0.25 - 2019-03-27
- Updated default log format.
- Add endpoints for `dbs`.
Expand Down
9 changes: 6 additions & 3 deletions docs/9-Log-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ AlibabaCloud::setLogger($logger);

### 默认格式
```text
"{method} {uri} HTTP/{version}" {code} {hostname} $pid
"{method} {uri} HTTP/{version}" {code} {cost} {hostname} {pid}
```

### 设置格式
Expand All @@ -41,8 +41,8 @@ AlibabaCloud::setLogFormat('{hostname} [{date_common_log}]');

日志内容支持以下变量替换:

| 变量 | 描述 |
|----------|:-------------:|
| 变量 | 描述 |
|----------|-------------|
| {request} | 完整的HTTP请求消息 |
| {response} | 完整的HTTP响应消息 |
| {ts} | GMT中的 ISO 8601日期 |
Expand All @@ -63,6 +63,9 @@ AlibabaCloud::setLogFormat('{hostname} [{date_common_log}]');
| {res_headers} | 响应头 |
| {req_body} | 请求主体 |
| {res_body} | 响应主体 |
| {pid} | PID |
| {cost} | 耗时 |
| {start_time} | 开始时间 |

***
[← 调试](8-Debug-CN.md) | 日志[(English)](9-Log-EN.md) | [测试 →](10-Test-CN.md)
9 changes: 6 additions & 3 deletions docs/9-Log-EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ AlibabaCloud::setLogger($logger);

### Default Format
```text
"{method} {uri} HTTP/{version}" {code} {hostname} $pid
"{method} {uri} HTTP/{version}" {code} {cost} {hostname} {pid}
```

### Set Format
Expand All @@ -41,8 +41,8 @@ AlibabaCloud::setLogFormat('{hostname} [{date_common_log}]');

The following variable substitutions are supported:

| Variable | Describe |
|----------|:-------------:|
| Variable | Describe |
|----------|-------------|
| {request} | Full HTTP request message |
| {response} | Full HTTP response message |
| {ts} | ISO 8601 date in GMT |
Expand All @@ -63,6 +63,9 @@ The following variable substitutions are supported:
| {res_headers} | Response headers |
| {req_body} | Request body |
| {res_body} | Response body |
| {pid} | PID |
| {cost} | Cost Time |
| {start_time} | Start Time |

***
[← Debug](8-Debug-EN.md) | Log[(中文)](9-Log-CN.md) | [Test →](10-Test-EN.md)
2 changes: 1 addition & 1 deletion src/AlibabaCloud.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class AlibabaCloud
/**
* Version of the Client
*/
const VERSION = '1.0.25';
const VERSION = '1.0.26';

/**
* This static method can directly call the specific service.
Expand Down
77 changes: 77 additions & 0 deletions src/Log/LogFormatter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

namespace AlibabaCloud\Client\Log;

use DateTime;
use DateTimeZone;
use Exception;
use GuzzleHttp\MessageFormatter;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

/**
* Class LogFormatter
*
* @package AlibabaCloud\Client\Log
*/
class LogFormatter extends MessageFormatter
{
/**
* @var float
*/
private static $logStartTime = 0;
/**
* @var DateTime
*/
private static $ts;

/** @var string Template used to format log messages */
public $template;

/**
* @param string $template Log message template
*
* @throws Exception
*/
public function __construct($template)
{
parent::__construct($template);
self::$logStartTime = microtime(true);
$this->template = $template;
$timezone = new DateTimeZone(date_default_timezone_get() ?: 'UTC');
if (PHP_VERSION_ID < 70100) {
self::$ts = DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true)), $timezone);
} else {
self::$ts = new DateTime(null, $timezone);
}
}

/**
* @return float|mixed
*/
private static function getCost()
{
return microtime(true) - self::$logStartTime;
}

/**
* Returns a formatted message string.
*
* @param RequestInterface $request Request that was sent
* @param ResponseInterface $response Response that was received
* @param Exception $error Exception that was received
*
* @return string
*/
public function format(
RequestInterface $request,
ResponseInterface $response = null,
Exception $error = null
) {
$this->template = str_replace('{pid}', getmypid(), $this->template);
$this->template = str_replace('{cost}', self::getCost(), $this->template);
$this->template = str_replace('{start_time}', self::$ts->format('Y-m-d H:i:s.u'), $this->template);

return (new MessageFormatter($this->template))->format($request, $response, $error);
}
}
4 changes: 2 additions & 2 deletions src/Request/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use AlibabaCloud\Client\Filter\ClientFilter;
use AlibabaCloud\Client\Filter\Filter;
use AlibabaCloud\Client\Filter\HttpFilter;
use AlibabaCloud\Client\Log\LogFormatter;
use AlibabaCloud\Client\Request\Traits\AcsTrait;
use AlibabaCloud\Client\Request\Traits\ClientTrait;
use AlibabaCloud\Client\Request\Traits\DeprecatedTrait;
Expand All @@ -24,7 +25,6 @@
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Uri;

Expand Down Expand Up @@ -388,7 +388,7 @@ public static function createClient()
if (AlibabaCloud::getLogger()) {
$stack->push(Middleware::log(
AlibabaCloud::getLogger(),
new MessageFormatter(AlibabaCloud::getLogFormat())
new LogFormatter(AlibabaCloud::getLogFormat())
));
}

Expand Down
4 changes: 1 addition & 3 deletions src/Traits/LogTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ public static function setLogFormat($formatter)
*/
public static function getLogFormat()
{
$pid = getmypid();

return self::$logFormat
?: "\"{method} {uri} HTTP/{version}\" {code} {hostname} $pid";
?: '"{method} {uri} HTTP/{version}" {code} {cost} {hostname} {pid}';
}
}
52 changes: 52 additions & 0 deletions tests/Mock/VirtualFile.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

namespace AlibabaCloud\Client\Tests\Mock;

use org\bovigo\vfs\vfsStream;

/**
* Class VirtualFile
*
* @package AlibabaCloud\Client\Tests\Mock
*/
class VirtualFile
{

/**
* @var string VirtualFile Content
*/
private $content;

/**
* VirtualFile constructor.
*
* @param string $content
*/
private function __construct($content)
{
$this->content = $content;
}

/**
* @param string $content
*
* @return VirtualFile
*/
public static function content($content = '')
{
return new static($content);
}

/**
* @param string $fileName
*
* @return string VirtualFile Filename
*/
public function url($fileName = 'file')
{
return vfsStream::newFile($fileName)
->withContent($this->content)
->at(vfsStream::setup('AlibabaCloud'))
->url();
}
}
2 changes: 1 addition & 1 deletion tests/Unit/Traits/LogTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function testLogger()
$logger = new Logger('AlibabaCloud');
$logger->pushHandler(new StreamHandler($logFile));
AlibabaCloud::setLogger($logger);
AlibabaCloud::setLogFormat('{uri} Custom field');
AlibabaCloud::setLogFormat('{start_time} "{method} {uri} HTTP/{version}" {code} {cost} {hostname} {pid} Custom field');

// Setup
$regionId = 'cn-hangzhou';
Expand Down

0 comments on commit c8405ac

Please sign in to comment.