Yii2 - How to set Time in Log messages?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 10:16:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!