问题
I am using EmailTarget
in Yii2 and I am logging messages like this.
Yii::info('Log message example','mail');
After successful execution, I am receiving mail like this:
2018-07-31 09:01:12 [127.0.0.1][user@example.com][-][info][mail] Log message example
By default Yii2 generating log messages and displaying time in GMT format.
How can I configure time in these log messages?
回答1:
This log target uses date()
for date formatting, so if you're getting date with wrong timezone, you probably have incorrect timezone settings in your PHP. You may use date_default_timezone_set() to change timezone used by date()
, for example in your config:
date_default_timezone_set('America/Los_Angeles');
See also list of available timezones.
If your log target should use different timezone than the rest of the application, you may create custom target and override getTime() in this way:
protected function getTime($timestamp) {
$oldTimezone = date_default_timezone_get();
date_default_timezone_set('UTC'); // <- put your timezone here
$parts = explode('.', StringHelper::floatToString($timestamp));
$result = date('Y-m-d H:i:s', $parts[0]) . ($this->microtime && isset($parts[1]) ? ('.' . $parts[1]) : '');
date_default_timezone_set($oldTimezone);
return $result;
}
回答2:
You can create a new class that extends from yii\log\EmailTarget
and overwrite the function formatMessage()
inherited form yii\Log\Target
.
Yii 2 Docs (log\Target) Github source
Then use that class in your configurations:
'components' => [
'log' => [
'targets' => [
[
'class' => 'your\namespace\CustomEmailTarget',
'mailer' => 'mailer',
'levels' => ['error', 'warning'],
'message' => [
'from' => ['log@example.com'],
'to' => ['developer1@example.com', 'developer2@example.com'],
'subject' => 'Log message',
],
],
],
],
],
来源:https://stackoverflow.com/questions/51942302/yii2-how-to-set-time-in-log-messages