How to maintain different log files for different purposes in Yii2
I eventually reverted back to using Yii2 logger by adding 2 additional file targets in my @app/config/main.php. The file targets had categories = ['orders'] and ['pushNotifications'] respectively so that in my code I use:
Yii::info($message, 'pushNotifications');
or
Yii::info($message, 'orders');
Here is my log config:
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['info'],
'categories' => ['orders'],
'logFile' => '@app/runtime/logs/Orders/requests.log',
'maxFileSize' => 1024 * 2,
'maxLogFiles' => 20,
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['info'],
'categories' => ['pushNotifications'],
'logFile' => '@app/runtime/logs/Orders/notification.log',
'maxFileSize' => 1024 * 2,
'maxLogFiles' => 50,
],
],
],
Since I wasn't quite sure how to configure Yii2 logger to do what I wanted, and googling the subject wasn't much help I decided to go with a third-party logger. The one I chose was Monolog. This functionality was only needed in one class so I create a static getLogger method which returned an instance of Monolog\Logger.
public static function getLogger($name) {
$logger = new \Monolog\Logger($name);
$logger->pushHandler(new \Monolog\Handlers\RotatingFileHandle(Yii::getAlias("@app/runtime/logs/$name.log")), \Monolog\Logger::INFO);
return $logger;
}
Then in sendRequest method I use:
static::getLogger('orders')->info($outgoingXmlPayload.$curlResponseXml);
In the processResponse method I use:
static::getLogger('pushNotifications')->info($notificationXml);
I will be glad to hear(or read) from anyone who has a better solution still. Thanks. --Ab