Differentiate between Frontend and Backend Logs in DBTarget Yii2 - yii2

I am logging into Db using existing Yii logging API.
But I want to differentiate between Frontend logs and Backend logs inside DB.
Everything that appears is common for both, I face difficulty tracing frontend logs.
Below is the image of DB Logs where GREEN marked are for backend logs, RED marked are for Frontend Logs.

You can use prefix property for this. This is callable that returns a string to be prefixed to every exported message with signature function ($message).
As default getMessagePrefix() is used there which prefixes the message with user IP, user ID and session ID.
You can use it to add there frontend and backend.

Thanks to #Bizley!
Inside both backend/config/main and frontend/config/main, I configured below; This is how my entire log configuration for Frontend looks like(Similarly you can do it for Backend);
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\DbTarget',
'levels' => ['error'],
'prefix' => function ($message) {
return "[Frontend]";
},
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['error','info'],
],
],
],
Below is the view on UI for logs. With the Help of Prefix I can now easily differentiate between channels.

Related

Yii2 internationalizating slug and controller

I'm making a yii2 site in 2 languages (for now) using yii's native i18n module, but how can I add multilanguage support for the action URLs?
For instance one of my actions is category/slug and in English, it will show as
http://example.com/category/chair
but in spanish it has to be shown as
http://example.com/categoria/silla
and so on for other languages shown in the future
right now im manually adding my routes like:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<alias:\w+>' => 'site/<alias>',
'marca/<slug>' => 'site/brand',
'categoria/<slug>' => 'site/category',
'brand/<slug>' => 'site/brand',
'category/<slug>' => 'site/category',
],
],
Do i need to manually route every action to its correct controller or is it possible to add a more automated form using yii::t() function?
you will need to write your own UrlRule class, implementing yii\web\UrlRuleInterface and configure your UrlManager.
read more here.
basically it is about "translating" a given request like '/categoria/silla' to your internal url ['site/category', 'slug' => $slug, 'lang' => $lang] in your UrlRule's 'parseRequest' method. 'createUrl' is the other way round.

yii2 page caching for single posts

I have blog via yii2 and using page caching
'class' => 'yii\filters\PageCache',
'only' => ['view','video'],
'duration' => 900,
'dependency' => [
'class' => 'yii\caching\DbDependency',
'sql' => '?',
],
my post table has primary key as id ;
how to I set sql as separate page cache per post id ?
thank you guy .
Just pass the current ID to it and yes, you can do it, use the enabled property and variation like this
[
'enabled' => Yii::$app->request->isGet && Yii::$app->user->isGuest,
'class' => 'yii\filters\PageCache',
'only' => ['index'],
'duration' => 900,
'variations' => [
Yii::$app->request->get('id')
]
]
This ensures that it will cache only get requests for non logged in users per post ID, you don't want to cache other request than get or logged in users if they can do some things like commenting and see per user data (login name etc.)
You can even use a more advanced config if you like eg. dynamic placeholder with page cache to allow caching even for authenticated users, just check the docs.

How to correctly specify migration namespace classes in yii2?

could someone explain me how can I correctly specify my modules migration namespaces? As I see in the documentation, it's:
return [
'controllerMap' => [
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => [
'app\migrations', // Common migrations for the whole application
'module\migrations', // Migrations for the specific project's module
'some\extension\migrations', // Migrations for the specific extension
],
],
],
];
But there are no explanation in which file should I write the commands. I've tried it in config.php, as:
'controllerMap' => [
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => [
'app\modules\adBoard\migrations',
],
But I don't know which controller class should I write. Could someone tell me in which file I have to specify it and how to specify it correctly?
If you refer to this documentation
Configuring Command Globally
Instead of entering the same option
values every time you run the migration command, you may configure it
once for all in the application configuration like shown below:
return [
'controllerMap' => [
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationTable' => 'backend_migration',
],
], ];
With the above configuration, each time you run the migration command, the backend_migration table will be used to record
the migration history. You no longer need to specify it via the
migrationTable command-line option.
Namespaced Migrations
Since 2.0.10 you can use namespaces for the
migration classes. You can specify the list of the migration
namespaces via migrationNamespaces. Using of the namespaces for
migration classes allows you usage of the several source locations for
the migrations. For example:
return [
'controllerMap' => [
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => [
'app\migrations', // Common migrations for the whole application
'module\migrations', // Migrations for the specific project's module
'some\extension\migrations', // Migrations for the specific extension
],
],
], ];
this config should be placed in you console/config/main.php
but for namespaced migration remeber that starting for 2.0.10
depending on your yii2-template application (basic or advanced) the location of "console" specific settings are located in different directories.
For basic template, console fetch settings from <app>/config/console.php file.
And for advanced template, you should edit <app>/console/config/main.php file.
Remember that your settings for console will not affect web-settings, so if you want to register some component in the whole project, you have to duplicate it in both files.
P.S. I would like to add one more detail about advanced template, is that it has common setting for frontend and backend sub-apps, which is located in <app>/common/config/main.php, but those settings are not common with console commands.
I would like to share my experience with Yii2 namespaced migrations.
Scenario
I am using advanced template.
I have 100s of old migrations in console/migrations folder.
I have new extension which have namespaced migrations.
I have new migrations in old folder console/migrations.
I want to create future migrations with namespaces in new folder console/migrations/namespaced. I want to keep all old migrations intact which are located at console/migrations.
console/config/main.php configurations worked for me.
return [
'controllerMap' => [
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationNamespaces' => [
'console\migrations\namespaced',
'yii\swiftsmser\migrations'
]
],
],
//.... more configurations
];
With above configurations, when I executed yii migrate, It includes all above mentioned folders.
Note: To create new migration. Just make sure to use command like below.
yii migrate/create console\\migrations\\namespaced\\DLTTemplatesForSMS

Automatic Logout after 5 minutes of inactive in yii2

May I know how to have function of automatic logout if users have inactive more than 5 minutes in yii2 ?
Try this configuration :
'user' => [
'enableAutoLogin' => false,
'authTimeout' => 300,
],
authTimeout
Your answer lies in configuration of "user" component in your config files.
Everything you need to know is in this documentation Yii2 User Component, set authTimout property to 300 (that's in seconds) and your user should be logged out after 5 minutes of inactivity.
In your component configuration you need to add config in user component like this
'components'=>[
'user' => [
'class'=>'yii\web\User',
'identityClass' => 'common\models\User',
'loginUrl'=>['sign-in/login'],
'enableAutoLogin' => false,
'authTimeout'=>300, //Number of second to Automatic Logout if inactive
//this config is optional
'identityCookie' => [
'name' => '_backendUser', // unique for backend
'path'=>'#backend/web' // correct path for the backend app.
],
'as afterLogin' => 'common\behaviors\LoginTimestampBehavior'
],
],
Besides of setting up the main.php I have three suggestion to handle this situation.
You should set you application in production mode ..
customize the site/error.php to check if user is guest and if not display the div with message like "Session expires" and a link to "site/login".
Alternatively, To redirect to login page when clicks on any link, define the access-control in a controller behaviors function and then you are done.

Yii2 mongodb: how to change database?

My application use many databases, they are in same structure, but data has no relation between different databases. I need to change database via request params.
In the config can only setup dsn, but I want to change database dynamically.
How can I do that.
I got myself:
$mongo = Yii::$app->get('mongodb');
$mongo->options['db'] = 'foo';
The simplest solution is to defined multiple connections in the configuration:
'components' =>
[
...
'mongodb' =>
[
'class' => '\yii\mongodb\Connection',
'dsn' => 'mongodb://localhost:27017/database1',
],
'othermongodb' =>
[
'class' => '\yii\mongodb\Connection',
'dsn' => 'mongodb://localhost:27017/database2',
],
...
]
You can then access your connections with Yii::$app->mongodb and Yii::$app->othermongodb (or using the get()-method if you prefer). This also allows you to specify the correct database for the ActiveRecord classes that come from a different database:
class MyOtherDBMongo extends \yii\mongodb\ActiveRecord
{
public static function getDb()
{
return \Yii::$app->get('othermongodb');
}
}