How to log errors once using FileTarget - php

I use the Yii component "log" to log some important info. In the targets I have:
[
'class' => FileTarget::class,
'categories' => ['import.category'],
'levels' => ['info', 'warning', 'error'],
'logFile' => '#runtime/logs/import/import.log',
'maxFileSize' => 10240,
'logVars' => []
]
I call the logger in this way:
Yii::warning('some message', 'import.category');
I have a record in logs/import/import.log. That is good. But I have the same record in logs/app.log.
I do not need the record in logs/app.log. Is this by default? Can I turn it off?
By the way, if I use:
Yii::info('some message', 'import.category');
I have a record only in logs/import/import.log, but an error or warning duplicates the record.

The configuration for your app.log target probably looks like this:
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
'logFile' => '#runtime/logs/app.log',
],
Because no categories are specified, all error and warning messages are written there. To exclude category from getting logged in target there is $except property in yii\log\Target which is common parent for log targets. So you want to modify your setting for app.log target like this:
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
'logFile' => '#runtime/logs/app.log',
'except' => ['import.category'],
],

Related

Yii Console Script, Login to User [duplicate]

I am trying to run a console controller from the terminal, but i am getting this errors every time
Error: Getting unknown property: yii\console\Application::user
here is the controller
class TestController extends \yii\console\Controller {
public function actionIndex() {
echo 'this is console action';
} }
and this is the concole config
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'modules' => [],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params];
I tried running it using these commands with no luck
php yii test/index
php yii test
php ./yii test
can anyone help please?
Console application does not have Yii->$app->user. So, you need to configure user component in config\console.php.
like as,
config\console.php
'components' => [
.........
......
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\User',
//'enableAutoLogin' => true,
],
'session' => [ // for use session in console application
'class' => 'yii\web\Session'
],
.......
]
More info about your problem see this : Link
OR
Visit following link :
Yii2 isGuest giving exception in console application
Note : There's no session in console application.
Set in \console\config\main.php
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\Credential',// class that implements IdentityInterface
//'enableAutoLogin' => true,
],
],
'params' => $params,
];
now in your \console\controller\AbcController.php add init method
public function init() {
parent::init();
Yii::$app->user->setIdentity(Credential::findOne(['id'=><cronloginid>]));
}
create a cron login and pass that login id in variable with this config your Blameable Behavior of yii2 will work
As #GAMITG said, you must config user component in config file, but unfortunately, you couldn't access session in console, that's because session is not available in console. Maybe you could solve the problem like this:
$user_id = isset(Yii::$app->user->id) ? Yii::$app->user->id : 0;

Yii2 - Logging 500 errors on production

Im trying to debug an Internal Server Error on production that runs Yii2.
To do this, I added EmailTarget to my config file as follows
if(!YII_DEBUG){
$logTarget[] = [
'class' => 'yii\log\EmailTarget',
'mailer' =>'mailer',
'levels' => ['error'],
'message' => [
'from' => ['mail#example.com'],
'to' => ['mymail#example.com'],
'subject' => 'Log',
],
'categories' => [
'yii\db\*',
'yii\web\HttpException:*',
],
'except' => [
'yii\web\HttpException:404',
'yii\web\HttpException:403',
'yii\web\HttpException:401'
]
];
}
then
'log' => [
'traceLevel' => 3,
'targets' => $logTarget,
],
Im not getting the 500 errors though. Am I doing smt wrong? Or are 500 errors not logged by default
So finally got it working.
Apparently, the 'categories' here blocked 500 errors from being sent probably since most 500 errors belong to yii\base\Excetion and not yii\web\HttpException.
Since, by default, if no 'categories' are put, all the errors are included, just removing this from the array fixed the problem.
My fixed array is:
if(!YII_DEBUG){
$logTarget[] = [
'class' => 'yii\log\EmailTarget',
'mailer' =>'mailer',
'levels' => ['error'],
'message' => [
'from' => ['mail#example.com'],
'to' => ['mymail#example.com'],
'subject' => 'Log',
],
'except' => [
'yii\web\HttpException:404',
'yii\web\HttpException:403',
'yii\web\HttpException:401'
]
];
}

Yii2: How do I debug console commands?

The Yii2 debugger seems to only work for web requests. How can I debug console commands (CLI)?
Eg. I need to see the SQL statements that were executed during a console command...
Use logger:
'log' => [
'targets' => [[
...
], [
'class' => 'yii\log\FileTarget',
'logFile' => '#runtime/logs/profile.log',
'logVars' => [],
'levels' => ['profile'],
'categories' => ['yii\db\Command::query'],
'prefix' => function($message) {
return '';
}
]]
]
https://github.com/achertovsky/yii2-debug-cli
i wrote extension to existing yii2-debug to achieve the result. Please, use and lmk issues if you find some.
In the Yii2 default application advanced template, you already have the log file target setup/enabled. However, it is only enabled for 'error' and 'warning' conditions. To include for info, add info as below in the console/config/main.php
[
'class' => 'yii\log\FileTarget',
'levels' => ['info', 'error', 'warning'],
],
The log output should be in console/runtime/logs/app.log

Yii2 - Getting unknown property: yii\console\Application::user

I am trying to run a console controller from the terminal, but i am getting this errors every time
Error: Getting unknown property: yii\console\Application::user
here is the controller
class TestController extends \yii\console\Controller {
public function actionIndex() {
echo 'this is console action';
} }
and this is the concole config
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'modules' => [],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params];
I tried running it using these commands with no luck
php yii test/index
php yii test
php ./yii test
can anyone help please?
Console application does not have Yii->$app->user. So, you need to configure user component in config\console.php.
like as,
config\console.php
'components' => [
.........
......
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\User',
//'enableAutoLogin' => true,
],
'session' => [ // for use session in console application
'class' => 'yii\web\Session'
],
.......
]
More info about your problem see this : Link
OR
Visit following link :
Yii2 isGuest giving exception in console application
Note : There's no session in console application.
Set in \console\config\main.php
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\Credential',// class that implements IdentityInterface
//'enableAutoLogin' => true,
],
],
'params' => $params,
];
now in your \console\controller\AbcController.php add init method
public function init() {
parent::init();
Yii::$app->user->setIdentity(Credential::findOne(['id'=><cronloginid>]));
}
create a cron login and pass that login id in variable with this config your Blameable Behavior of yii2 will work
As #GAMITG said, you must config user component in config file, but unfortunately, you couldn't access session in console, that's because session is not available in console. Maybe you could solve the problem like this:
$user_id = isset(Yii::$app->user->id) ? Yii::$app->user->id : 0;

How to maintain different log files for different purposes in Yii2

I am using Yii2 for a project. I have a class for consuming a third party service. This class has two methods sendRequest and processResponse. I would like to maintain separate logs for payload in sendRequest before actually sending it and another log for the raw response data received in processResponse before doing any processing. Additionally I would like log rotation on both logs as the files may grow indefinitely and want both files to be separate from the default app.log. Is this possible? How may I implement this using Yii2 APIs?
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
Asterisk * may also come handy if we need to collect more subcategories into a cummulative file:
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'flushInterval' => 100, // may prevent from memory exhaustion
'targets' => [
[
'class' => 'yii\log\FileTarget',
'categories' => ['eshop1*'],
'logFile' => '#app/runtime/logs/eshop1.log',
'logVars' => [], // don't log global vars
],
[
'class' => 'yii\log\FileTarget',
'categories' => ['eshop2*'],
'logFile' => '#app/runtime/logs/eshop2.log',
'logVars' => ['GET', 'POST'], // log some globals
'exportInterval' => 100, // may prevent from memory exhaust
],
],
],
This work for me, for dev log
'components' => [
'log' => [
'traceLevel' => YII_DEBUG ? 10 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'logFile' => '#runtime/logs/dev.log',
'categories' => ['dev'],
'levels' => ['trace'],
],
],
],
it's used
Yii::debug('log step 1', 'dev');

Categories