Skip to content

Commit

Permalink
Refactor unit test structure and add Logger unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
huangzhhui committed Mar 20, 2018
1 parent bb995ba commit 9c4d386
Show file tree
Hide file tree
Showing 37 changed files with 533 additions and 221 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ temp/
.phpintel/
.DS_Store
/.php_cs.cache
test/runtime
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
},
"autoload-dev": {
"psr-4": {
"Swoft\\Test\\": "test"
"SwoftTest\\": "test/Cases"
}
},
"repositories": {
Expand Down
124 changes: 58 additions & 66 deletions src/Log/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Swoft\Log;

use Swoft\App;
use Swoft\Core\Coroutine;
use Swoft\Core\RequestContext;

Expand Down Expand Up @@ -76,18 +77,17 @@ class Logger extends \Monolog\Logger
/**
* @var array 日志级别对应名称
*/
protected static $levels
= array(
self::DEBUG => 'debug',
self::INFO => 'info',
self::NOTICE => 'notice',
self::WARNING => 'warning',
self::ERROR => 'error',
self::CRITICAL => 'critical',
self::ALERT => 'alert',
self::EMERGENCY => 'emergency',
self::TRACE => 'trace'
);
protected static $levels = array(
self::DEBUG => 'debug',
self::INFO => 'info',
self::NOTICE => 'notice',
self::WARNING => 'warning',
self::ERROR => 'error',
self::CRITICAL => 'critical',
self::ALERT => 'alert',
self::EMERGENCY => 'emergency',
self::TRACE => 'trace'
);

public function __construct()
{
Expand All @@ -99,19 +99,18 @@ public function __construct()
* @param int $level 日志级别
* @param mixed $message 信息
* @param array $context 附加信息
*
* @return bool
*/
public function addRecord($level, $message, array $context = array())
{
if (!$this->enable) {
if (! $this->enable) {
return true;
}

$levelName = static::getLevelName($level);

if (!static::$timezone) {
static::$timezone = new \DateTimeZone(date_default_timezone_get() ?: 'UTC');
if (! static::$timezone) {
static::$timezone = new \DateTimeZone(date_default_timezone_get() ? : 'UTC');
}

// php7.1+ always has microseconds enabled, so we do not need this hack
Expand All @@ -133,7 +132,7 @@ public function addRecord($level, $message, array $context = array())

$this->messages[] = $record;

if (count($this->messages) >= $this->flushInterval) {
if (App::$isInTest || \count($this->messages) >= $this->flushInterval) {
$this->flushLog();
}

Expand All @@ -149,14 +148,13 @@ public function addRecord($level, $message, array $context = array())
* @param string $levelName 级别名
* @param \DateTime $ts 时间
* @param array $extra 附加信息
*
* @return array
*/
public function formateRecord($message, $context, $level, $levelName, $ts, $extra)
{
$record = array(
"logid" => RequestContext::getLogid(),
"spanid" => RequestContext::getSpanid(),
'logid' => RequestContext::getLogid(),
'spanid' => RequestContext::getSpanid(),
'messages' => $message,
'context' => $context,
'level' => $level,
Expand All @@ -177,19 +175,19 @@ public function formateRecord($message, $context, $level, $levelName, $ts, $extr
*/
public function pushLog($key, $val)
{
if (!$this->enable || !(is_string($key) || is_numeric($key))) {
if (! $this->enable || ! (\is_string($key) || is_numeric($key))) {
return;
}

$key = urlencode($key);
$cid = Coroutine::tid();
if (is_array($val)) {
if (\is_array($val)) {
$this->pushlogs[$cid][] = "$key=" . json_encode($val);
} elseif (is_bool($val)) {
} elseif (\is_bool($val)) {
$this->pushlogs[$cid][] = "$key=" . var_export($val, true);
} elseif (is_string($val) || is_numeric($val)) {
} elseif (\is_string($val) || is_numeric($val)) {
$this->pushlogs[$cid][] = "$key=" . urlencode($val);
} elseif (is_null($val)) {
} elseif (\is_null($val)) {
$this->pushlogs[$cid][] = "$key=";
}
}
Expand All @@ -201,7 +199,7 @@ public function pushLog($key, $val)
*/
public function profileStart($name)
{
if (!$this->enable || is_string($name) == false || empty($name)) {
if (! $this->enable || \is_string($name) === false || empty($name)) {
return;
}
$cid = Coroutine::tid();
Expand All @@ -215,20 +213,20 @@ public function profileStart($name)
*/
public function profileEnd($name)
{
if (!$this->enable || is_string($name) == false || empty($name)) {
if (! $this->enable || \is_string($name) === false || empty($name)) {
return;
}

$cid = Coroutine::tid();
if (!isset($this->profiles[$cid][$name])) {
if (! isset($this->profiles[$cid][$name])) {
$this->profiles[$cid][$name] = [
'cost' => 0,
'total' => 0,
];
}

$this->profiles[$cid][$name]['cost'] += microtime(true) - $this->profileStacks[$cid][$name]['start'];
$this->profiles[$cid][$name]['total'] = $this->profiles[$cid][$name]['total'] + 1;
$this->profiles[$cid][$name]['cost'] += microtime(true) - $this->profileStacks[$cid][$name]['start'];
$this->profiles[$cid][$name]['total'] += 1;
}

/**
Expand All @@ -238,16 +236,16 @@ public function getProfilesInfos()
{
$profileAry = [];
$cid = Coroutine::tid();
$profiles = $this->profiles[$cid]?? [];
$profiles = $this->profiles[$cid] ?? [];
foreach ($profiles as $key => $profile) {
if (!isset($profile['cost']) || !isset($profile['total'])) {
if (! isset($profile['cost']) || ! isset($profile['total'])) {
continue;
}
$cost = sprintf("%.2f", $profile['cost'] * 1000);
$cost = sprintf('%.2f', $profile['cost'] * 1000);
$profileAry[] = "$key=" . $cost . '(ms)/' . $profile['total'];
}

return implode(",", $profileAry);
return implode(',', $profileAry);
}

/**
Expand All @@ -259,17 +257,17 @@ public function getProfilesInfos()
*/
public function counting($name, $hit, $total = null)
{
if (!is_string($name) || empty($name)) {
if (! \is_string($name) || empty($name)) {
return;
}

$cid = Coroutine::tid();
if (!isset($this->countings[$cid][$name])) {
if (! isset($this->countings[$cid][$name])) {
$this->countings[$cid][$name] = ['hit' => 0, 'total' => 0];
}
$this->countings[$cid][$name]['hit'] += intval($hit);
$this->countings[$cid][$name]['hit'] += \intval($hit);
if ($total !== null) {
$this->countings[$cid][$name]['total'] += intval($total);
$this->countings[$cid][$name]['total'] += \intval($total);
}
}

Expand All @@ -279,15 +277,15 @@ public function counting($name, $hit, $total = null)
public function getCountingInfo()
{
$cid = Coroutine::tid();
if (!isset($this->countings[$cid]) || empty($this->countings[$cid])) {
return "";
if (! isset($this->countings[$cid]) || empty($this->countings[$cid])) {
return '';
}

$countAry = [];
$countings = $this->countings[$cid];
foreach ($countings as $name => $counter) {
if (isset($counter['hit'], $counter['total']) && $counter['total'] != 0) {
$countAry[] = "$name=" . $counter['hit'] . "/" . $counter['total'];
foreach ($countings ?? [] as $name => $counter) {
if (isset($counter['hit'], $counter['total']) && $counter['total'] !== 0) {
$countAry[] = "$name=" . $counter['hit'] . '/' . $counter['total'];
} elseif (isset($counter['hit'])) {
$countAry[] = "$name=" . $counter['hit'];
}
Expand All @@ -299,12 +297,11 @@ public function getCountingInfo()
* 写入日志信息格式化
*
* @param $message
*
* @return string
*/
public function formatMessage($message)
{
if (is_array($message)) {
if (\is_array($message)) {
return json_encode($message);
}
return $message;
Expand All @@ -314,13 +311,12 @@ public function formatMessage($message)
* 计算调用trace
*
* @param $message
*
* @return string
*/
public function getTrace($message)
{
$traces = debug_backtrace();
$count = count($traces);
$count = \count($traces);
$ex = '';
if ($count >= 7) {
$info = $traces[6];
Expand All @@ -339,7 +335,7 @@ public function getTrace($message)
}
}

if (!empty($ex)) {
if (! empty($ex)) {
$message = "trace[$ex] " . $message;
}

Expand Down Expand Up @@ -374,46 +370,43 @@ public function flushLog()
*/
public function appendNoticeLog($flush = false)
{
if (!$this->enable) {
if (! $this->enable) {
return;
}
$cid = Coroutine::tid();
$ts = $this->getLoggerTime();

// php耗时单位ms毫秒
$timeUsed = sprintf("%.2f", (microtime(true) - $this->getRequestTime()) * 1000);
$timeUsed = sprintf('%.2f', (microtime(true) - $this->getRequestTime()) * 1000);

// php运行内存大小单位M
$memUsed = sprintf("%.0f", memory_get_peak_usage() / (1024 * 1024));
$memUsed = sprintf('%.0f', memory_get_peak_usage() / (1024 * 1024));

$profileInfo = $this->getProfilesInfos();
$countingInfo = $this->getCountingInfo();
$pushlogs = $this->pushlogs[$cid]??[];
$pushlogs = $this->pushlogs[$cid] ?? [];

$messageAry = array(
"[$timeUsed(ms)]",
"[$memUsed(MB)]",
"[{$this->getUri()}]",
"[" . implode(" ", $pushlogs) . "]",
"profile[" . $profileInfo . "]",
"counting[" . $countingInfo . "]"
'[' . implode(' ', $pushlogs) . ']',
'profile[' . $profileInfo . ']',
'counting[' . $countingInfo . ']'
);


$message = implode(" ", $messageAry);
$message = implode(' ', $messageAry);

unset($this->profiles[$cid]);
unset($this->countings[$cid]);
unset($this->pushlogs[$cid]);
unset($this->profileStacks[$cid]);
unset($this->profiles[$cid], $this->countings[$cid], $this->pushlogs[$cid], $this->profileStacks[$cid]);

$levelName = self::$levels[self::NOTICE];
$message = $this->formateRecord($message, [], self::NOTICE, $levelName, $ts, []);

$this->messages[] = $message;

// 一个请求完成刷新一次或达到刷新的次数
$isReached = count($this->messages) >= $this->flushInterval;
$isReached = \count($this->messages) >= $this->flushInterval;
if ($this->flushRequest || $isReached || $flush) {
$this->flushLog();
}
Expand All @@ -426,8 +419,8 @@ public function appendNoticeLog($flush = false)
*/
private function getLoggerTime()
{
if (!static::$timezone) {
static::$timezone = new \DateTimeZone(date_default_timezone_get() ?: 'UTC');
if (! static::$timezone) {
static::$timezone = new \DateTimeZone(date_default_timezone_get() ? : 'UTC');
}

// php7.1+ always has microseconds enabled, so we do not need this hack
Expand Down Expand Up @@ -459,7 +452,6 @@ public function initialize()
*
* @param $message 日志信息
* @param array $context 附加信息
*
* @return bool
*/
public function addTrace($message, array $context = array())
Expand All @@ -483,7 +475,7 @@ public function setFlushInterval(int $flushInterval)
private function getUri()
{
$contextData = RequestContext::getContextData();
$uri = $contextData['uri']?? "";
$uri = $contextData['uri'] ?? '';
return $uri;
}

Expand All @@ -495,7 +487,7 @@ private function getUri()
private function getRequestTime()
{
$contextData = RequestContext::getContextData();
$requestTime = $contextData['requestTime']?? 0;
$requestTime = $contextData['requestTime'] ?? 0;
return $requestTime;
}
}
24 changes: 24 additions & 0 deletions test/Cases/AbstractTestCase.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php
/**
* This file is part of Swoft.
*
* @link https://swoft.org
* @document https://doc.swoft.org
* @contact [email protected]
* @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE
*/

namespace SwoftTest;

use PHPUnit\Framework\TestCase;

/**
* @uses AbstractTestCase
* @version 2017年11月03日
* @author huangzhhui <[email protected]>
* @copyright Copyright 2010-2017 Swoft software
* @license PHP Version 7.x {@link http://www.php.net/license/3_0.txt}
*/
class AbstractTestCase extends TestCase
{
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
<?php

namespace Swoft\Test\Testing\Aop;
/**
* This file is part of Swoft.
*
* @link https://swoft.org
* @document https://doc.swoft.org
* @contact [email protected]
* @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE
*/
namespace SwoftTest\Aop;

use Swoft\Aop\JoinPoint;
use Swoft\Aop\ProceedingJoinPoint;
Expand Down
Loading

0 comments on commit 9c4d386

Please sign in to comment.