Yii2 - How can I remove unnecessary information fr

2019-06-01 09:57发布

问题:

I am trying to log messages in Yii2 which are then emailed to my specified email address.

config file web.php contains:

'mail' => [
                    'class' => 'yii\log\EmailTarget',
                    'categories' => ['mail'],
                    'logVars' => [],
                    'mailer' => 'mailer',
                    'message' => [
                        'from' => ['user@example.com'],
                        'to' => ['user1@example.com'],
                        'subject' => 'Log message',
                    ],
                ],

I am logging message 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

So what I am trying to do is that I want to remove unwanted information like IP address, User Name etc. from this messages and at the end what I want is

2018-07-31 09:01:12 Log message example

回答1:

You can remove first three parts from log by setting prefix property:

'mail' => [
    'class' => 'yii\log\EmailTarget',
    'categories' => ['mail'],
    'logVars' => [],
    'prefix' => function () {
        return '';
    },
    'mailer' => 'mailer',
    'message' => [
        'from' => ['user@example.com'],
        'to' => ['user1@example.com'],
        'subject' => 'Log message',
    ],
],

Last two parts (level and category) are hardcoded, you need to extend EmailTarget and override formatMessage() to remove them.



回答2:

You can set this either in your configuration file web.php or in your code.

Yii::$app->log->targets['test']->prefix = function (){
        return null;
};

or

'mail' => [
       'class' => 'yii\log\EmailTarget',
       'categories' => ['mail'],
       'logVars' => [],
       'mailer' => 'mailer',
       'prefix' => function () {
           return null;
       },
       'message' => [
       'from' => ['user@example.com'],
       'to' => ['user1@example.com'],
       'subject' => 'Log message',
     ],
],