i have a little problem.
I'm developing a php application using Yii2 framework and i want to save a log messagges into db table.
I'm coding my own component witch extends DbTarget, in this component i rewrite export() function to save data into my table. It's works fine, but i can't get the log message.
For example, when i call Yii:log('message log'), all my data are saved in my db except 'message log' because i don't know how to get this value in my component.
Any solutions?
thanks
P.s. I'm newbee with yii2 and i have read the official documentation, but i didn't find any solution.
It seems you should specify level of the message
Yii:log('message log', Logger::LEVEL_TRACE);
or use shortcut methods
Yii::info('message log');
Yii::trace('message log');
Yii::error('message log');
Check your config for another targets. May be your message goes to level or category of another target. Notice that default category is 'application'.
To be shure you can make this configuration
'components' => [
'log' => [
'targets' => [
[
'class' => 'YourDbTarget',
'levels' => ['info'],
'categories' => ['application'],
],
],
],
],
And try to log info message
Yii::info('message log'); // target = info, category = application
Related
i'm trying to implement mdmsoft/yii2-admin with advanced template with this pull request
but when i try add route to menu get error "Route "x" not found."
if i try force add route via database the menu show an empty array.
for this you need to create one inside config/main.php
'urlManager' => [
'enablePrettyUrl' => true,
'rules' => [
'test/' => site(ControllerName)/test(actionName),
]
];
Let me know was this helpful or not.
I am using the Yii2 Framework and I am translating all texts of buttons, labels, messages, etc.
Then I read this article http://www.yiiframework.com/doc-2.0/guide-tutorial-i18n.html that shows how to do it automatically but I don't understand it.
I want to translate to Spanish from Argentina: es-AR or at least to any Spanish.
So I think I need to change from en-US to es-AR but I would like to know which files should I change.
Also I am using the great Gii code generator where I can see a checkbox called Enable I18N.
I watched these files but I am not sure if I am looking the right files:
vendor/yiisoft/yii2/base/Application.php
vendor/yiisoft/yii2/i18n/I18N.php
common/config/main-local.php
Add language propery and i18n component in application config. For advanced application template in common/config/main.php
return [
'language' => 'es-AR',
...
'components' => [
...
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#app/messages',
],
],
],
...
],
]
Use Yii::t() for all user messages (model labels, views, error messages etc).
echo \Yii::t('app', 'Friend');
Create directory messages/es-AR. Create file app.php in this directory and add translations
return [
'Friend' => 'Amigo',
'Girl' => 'Сhica',
...
];
Try to look into the official documentation, it is best tutorial for you. http://www.yiiframework.com/doc-2.0/guide-tutorial-i18n.html
Also, look at this answer yii2 basic multiple language
You can change default language by changing 'language' parameter of your main configuration file. Like this:
return
[
// set target language to be English
'language' => 'en-US',
]
Where instead 'en-US' you must to set needed locale code, e.g. 'es-AR'
I'm tightening up the logging for our Yii2 application and are struggling with getting the Logger to actually write messages to a log file when dealing with specific categories.
Our project consists of the following Yii2 'Applications' : console, common, frontend, backend and the logging for each of these components work fine for Exceptions generated by Yii and general PHP Exceptions. However when I add some info messages for a specific category in the console part (which I execute by running commands via SHH) the directory that the file should be in is created but the file itself is not. I see that the newly specified log messages are inside the correct 'FileTarget' when I do a var_dump of it.
I've set the flushInterval of the 'log' component to 1 and the exportInterval of the logTarget to 1 to make sure that the messages are to be written to the targets directly. I'm aware that this should be set to a larger value at some point, but for now I want to make sure that the logs are actually being saved. Changing the interval values doesn't seem to have any effect.
A workaround I came up with is to manually call target->export() for the specific FileTarget. This is how I currently make sure logs are being written:
In the Controller where I want to log message I do
Yii::info('Report created succesfully.', 'reports-create');
UtilitiesController::forceLogExport('reports-create');
The forceLogExport method does this:
public function forceLogExport($categoryName = ''){
$logger = \Yii::getLogger();
foreach($logger->dispatcher->targets as $target){
if(!empty($categoryName)){
foreach($target->categories as $category){
if($category == $categoryName){
$target->export();
}
}
}
}
$logger->flush(true);
}
This does actually write the logs to the .log file, however there seem to be duplicate entries in the log now and it feels just plain wrong to call an export after every message.
As I read in the docs the actual writing of logs only happens when either these intervals are met OR when the application ends. I could imagine the application not ending properly so I tried forcing this by calling Yii:$app->end() directly after logging the message, but the file stays empty.
Since the problem is neither the application not ending (I can see that it does end) nor the interval being met (I see at least one message in the target and the interval is set to 1) I'm kind of at my wit's end why the logs are not exported. If anyone could perhaps elaborate any further on when/where Yii calls the ->export() method itself that would be a big help.
EDIT: added the console/config/main.php settings. Slightly changed my story, initially I wrote that 'the log file was being created but the messages were not being written in it.' but in fact only the directory that should contain the files was created, not the log file itself.
<?php
return [
'id' => 'console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\User',
//'enableAutoLogin' => true,
],
'session' => [ // for use session in console application
'class' => 'yii\web\Session'
],
'log' => [
'flushInterval' => 1,
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error','info', 'warning'],
'categories' => ['reports-schedule'],
'exportInterval' => 1,
'logVars' => [null],
'logFile' => '#app/../logs/console/'. date('Y') . '/' . date('m') . '/reports-schedule/' . 'reports-schedule_' . date('d-m-Y') . '.log'
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['error','info', 'warning'],
'categories' => ['reports-create'],
'exportInterval' => 1,
'logVars' => [null],
'logFile' => '#app/../logs/console/'. date('Y') . '/' . date('m') . '/reports-create/' . 'reports-create_' . date('d-m-Y') . '.log'
],
// and 6 other similarly structured targets
[...],
[...],
[...],
[...],
[...],
[...],
],
]
];
UPDATE: it seems like I'll have to stick to manually calling ->export() on the desired log target. The problem I had with duplicate log entries (same message, same timestamp) being written was due to the fact that I had set the exportInterval property to 1 for the target (which I initially did to make sure the messages were exported at all). I suppose the logger stores messages until the value of exportInterval is met and then expect those messages to be written to the targets. I fixed duplicate entries from being written by removed the exportInterval property so Yii takes the default value (1000). For my case this would be sufficient since I wouldn't run into those numbers but for anyone reading this please consider your use case and check if you would run into anything close to that in a single cycle.
I had a similar issue at some point and I think this should be sufficient enough for your case.
Yii::$app->log->targets['reports-schedule']->logFile = $logPath;
Yii::info($message, $category);
Yii::getLogger()->flush();
This way you can specify a dynamic log path inside your schedule target and after flush the logger continues as it should.
Right now I'm trying to implement themming for my Yii2 based project.
How I see the thing now:
User chooses an application theme from the list on the settings
page in backend.
Using yii2-settings I'm saving all the
configuration data in DB (pretty easy).
In the application
bootstrap.php I'm creating new alias called #theme. Basically it
should lead us to a application theme base path (used in search
paths, assets manager, e.t.c.).
According to official
documentation, that's how I configured my view component:
'view' => [
'theme' => [
'basePath' => '#theme',
'baseUrl' => '#theme',
'pathMap' => [
'#app/views' => '#theme',
'#app/widgets' => '#theme/widgets',
'#app/modules' => '#theme/modules',
],
],
],
An issue I have is with p.3. According to yii2-settings documentation that's how I supposed to read the settings:
$theme = Yii::$app->settings->get('name', 'general');
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/$theme"));
But obviously, it's not working for me because of yii2-settings component didn't initialized yet when bootstrap.php is called. I've been trying to initialize it later in the init() method of my base controller, then adjust other aliases manually, but I feel that way being somewhat 'unclean', and also it still fails because of #theme alias is also used in asset file which is Yii2 starting to publish before calling the controller's init method.
So does anyone has any thoughts of how to do that 'hacking' the code as less as possible? I know I could just move configuration to some file, then read it manually before the application initialization, but it's still not the way I want to go.
Maybe there's some way to override some system component to set the alias after db component is loaded, but before view component configuration? Or Yii loads this components in a different order? Anyway. Any help would be appreciated!
You could try an Application Event in bootstrap:
\Yii::$app->on(\yii\base\Application::EVENT_BEFORE_REQUEST, function ($event) {
$theme = Yii::$app->settings->get('name', 'general');
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/$theme"));
});
OR in configuration file:
[
'on beforeRequest' => function ($event) {
// ...
},
]
From Yii 2 docs:
EVENT_BEFORE_REQUEST This event is triggered before an application
handles a request. The actual event name is beforeRequest.
When this event is triggered, the application instance has been
configured and initialized. So it is a good place to insert your
custom code via the event mechanism to intercept the request handling
process. For example, in the event handler, you may dynamically set
the yii\base\Application::$language property based on some parameters.
Here's the final solution:
config/bootstrap.php:
// Setting a temporary path for components configuration - will be changed later
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/"));
config/main.php
'components' => [
'view' => [
'theme' => [
'basePath' => '#theme',
'baseUrl' => '#theme',
'pathMap' => [
'#app/views' => '#theme',
'#app/widgets' => '#theme/widgets',
'#app/modules' => '#theme/modules',
],
],
],
],
'on beforeRequest' => function ($event) {
$theme = Yii::$app->settings->get('theme', 'general');
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/$theme"));
},
I have created a simple application in YII2 and it is working fine at my local machine but giving me Not Found (#404) "Page Not Found" error on live server.
Local URL: http://localhost:8080/basicapp/web/index.php?r=adminPanel%2Fstatemaster%2Findex
Live URL: http://XXXX.com/web/index.php?r=adminPanel%2Fstatemaster%2Findex
I am not using pretty URL, and didn't change in web.php. just added module info in the file. Code Snippet:
'modules' => [
'adminpanel' => [
'class' => 'app\admin\adminpanel',
],
'studentPanel' => [
'class' => 'app\Student\dashboard',
],
],
I can provide detial, whatever is required.
If anyone have similar problem, Just change your naming of models and controllers.
In my problem, model and controller names were like StateMasterController etc but it should be StatemasterController, mind the M.
It works for me, may be this can help you.
Thanks