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'
]
];
}
Related
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'],
],
I am unable to access default endpoints with pluralize option, view action is also not working
Case 1: Access without configure Module
'controllerNamespace' => 'api\controllers',
...
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'country',
'tokens' => [
'{id}' => '<id:\\w+>'
],
/*'pluralize'=>false,*/
],
]
http://localhost/api/web/countries Not working
http://localhost/api/web/country is working fine
http://localhost/api/web/country/1 is Not working
Case 2: Access via module v1
'modules' => [
'v1' => [
'basePath' => '#app/modules/v1',
'class' => 'api\modules\v1\Module'
]
],
...
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => ['country' => 'v1/country'],
'tokens' => [
'{id}' => '<id:\\w+>'
],
],
]
'pluralize' is not working completely and when access
v1/country & v1/country/12 both giving same result as index action (country list)
Your rule is incorrect you are missing the module name v1 in your rules
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/country',
'tokens' => [
'{id}' => '<id:\\w+>'
],
'extraPatterns' => [
'GET index' => 'index',
],
],
Now you can access it with
http://localhost/api/web/v1/countries
Note : in order to enable the POST request along with GET add it to the extra patterns like 'GET,POST index' => 'index',
I have a Laravel 5.6 project and I want to configure it such that high level errors are emailed to me.
I have added an email channel to logging.php config file and specified Monolog's Swiftmailer as the handler but since it needs a mailer instance and message in its constructor I don't know what values should be supplied.
Any help is much appreciated.
PS: I do know there are packages for this purpose but think this should be simple enough to do manually.
'email' => [
'driver' => 'monolog',
'handler' => Monolog\Handler\SwiftMailerHandler::class,
'handler_with' => [
'mailer' => ?,
'message' => ?,
],
],
With Lavarel 7.x you can solve it like this
'smtp-sys' => [
'driver' => 'monolog',
'level' => 'info',
'handler' => SwiftMailerHandler::class,
'handler_with' => [
'mailer' => new Swift_Mailer( (new Swift_SmtpTransport(env('MAIL_HOST_SYS'), env('MAIL_PORT_SYS'), env('MAIL_ENCRYPTION', 'tls')))->setUsername(env('MAIL_USERNAME_SYS'))->setPassword(env('MAIL_PASSWORD_SYS'))),
'message' => (new Swift_Message('[LOG] Exception'))
->setFrom([env('MAIL_USERNAME_SYS') => 'Dev'])
->setTo([env('MAIL_USERNAME_SYS') => 'Dev'])
],
],
It might be a little late but from Symfony SwiftMailer documentation you should use something like this:
...
'email' => [
'driver' => 'monolog',
'level' => 'critical',
'handler' => SwiftMailerHandler::class,
'handler_with' => [
'mailer' => (new Swift_SmtpTransport(env('MAIL_HOST'), env('MAIL_PORT'), env('MAIL_ENCRYPTION')))
->setUsername(env('MAIL_USERNAME'))
->setPassword(env('MAIL_PASSWORD')),
'message' => (new Swift_Message('[LOG] Exception'))
->setFrom([env('LOG_MAIL_FROM_ADDRESS') => env('LOG_MAIL_FROM_NAME')])
->setTo([env('LOG_MAIL_TO_ADDRESS') => 'Dev'])
->setBody('Here is the message itself')
],
'formatter' => HtmlFormatter::class,
],
...
I uploaded YII2 advanced my web app to online server.
I have 2 tables(companies,employees) and generated CRUD for these 2 tables.In main menu navigation given to view of company.
the below code i given on backend/views/layouts/main.php for navigation.
$menuItems = [
['label' => 'HOME', 'url' => ['/site/index']],
['label' => 'COMPANIES', 'url' => ['/companies/index']]
['label' => 'EMPLOYEES', 'url' => ['/employee/index']],
];
It's worked properly on localhost. But in online getting this exception.
Invalid Parameter – yii\base\InvalidParamException The view file does
not exist:
/home/echosoft/public_html/echosoftware/backend/views/companies/index.php
The file is existing in that folder.Please help me to solve this issue. I am stuck with this for 3 days.
This is backend\config.php codes
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'bootstrap' => ['log'],
'modules' => [],
'components' => [
'request' => [
'csrfParam' => '_csrf-backend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the backend
'name' => 'advanced-backend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
];
This may help.Thanks in advance.
try using
['label' => 'COMPANIES', 'url' => ['/companies/index']]
and if the localhost is windows and online server is unix/linux like be sure you have the proper case in the pathname filename
Windows in case insensitive in pathname unix is case sensitive
If in your backend\views you have the folder name with uppercase (backend\views\Companies) you should change with lower case (backend\views\companies) ..
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');