Log not working in yii2 - yii2

i want to put a log in app.log ,My config file
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
'file' => [
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
'logFile' => '#root/console/runtime/logs/app.log',
],
]
]
in controller action
public function actionRankCalculation()
{
$allConest = Contest::find()->where('isActive = 1')->all();
Yii::trace('start calculating average revenue');
$response = [];
/** #var Contest $contest */
foreach ($allConest as $contest) {
$videoQuery = Video::find()->where('contest_id = ' . $contest->id);
$videoQuery->andWhere('isActive = 1');
$videoQuery->orderBy([
'global_likes' => SORT_DESC,
'id' => SORT_ASC,
]);
}
But Yii::trace('start calculating average revenue'); not working

You try this.Use categories. For example like below
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error'],
'categories' => ['test1'],
'logFile' => '#app/Test/test1.log',
],
And use below one in controller action
public function actionIndex(){
Yii::error('Test index action', $category = 'test1'); }

Try to set both flushInterval and exportInterval to 1 in console config:
return [
'bootstrap' => ['log'],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'exportInterval' => 1,
],
],
'flushInterval' => 1,
],
],
];
It makes each log message appearing immediately in logs.

Related

yii2 how to view the logs of another .log file

I am using the yii2 framework with the 'queue' extension. This extension may fail, which is saved in the log file, and I would like to view the error in a specific view.
I was able to log errors into a specific .log file, so the real question is, how can I view errors from another log file?
Yii framework use category distinguish log file
config:
return [
'bootstrap' => ['log'],
'timeZone' => 'PRC',
'components' => [
'log' => [
'targets' => [
//default
[
'class' => 'yii\log\DbTarget',
'levels' => ['error', 'warning'],
],
//especially
[
'class' => 'yii\log\DbTarget',
'levels' => ['error'],
'categories' => ['yii\db\*'],//The point
'logFile'=>'log.txt',//you custom file
],
//especially2
[
'class' => 'yii\log\DbTarget',
'levels' => ['error'],
'categories' => ['app\models'],//The point
'logFile'=>'log.txt',//you custom file
],
//especially3
[
'class' => 'yii\log\DbTarget',
'levels' => ['error'],
'categories' => ['abc'],//The point
'logFile'=>'log.txt',//you custom file
],
],
],
],
];
Use it
Yii::trace('db error');
Yii::trace('start calculating average revenue', __METHOD__);
Yii::trace('start calculating average revenue', 'abc');
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
'error' =>
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
'categories' => ['yii\queue\Queue'],
'logFile' => '#runtime/logs/error.log',
//'enabled' => YII_DEBUG,
//'exportInterval' => 1,
],
],
],

Codeception Object configuration must be an array

I am trying to run basic codeception test but what I get is the error bellow:
Backend\tests.functional Tests (1) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
E LoginCest: Login user (0.01s)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1) LoginCest: Login user
Test tests/functional/LoginCest.php:loginUser
[yii\base\InvalidConfigException] Object configuration must be an array containing a "class" element.
Scenario Steps:
1. $I->amOnPage("/admin/user/login") at tests/functional/LoginCest.php:18
#1 /home/projects/toma/toma-coreshop/vendor/yiisoft/yii2/BaseYii.php:353
#2 /home/projects/toma/toma-coreshop/vendor/yiisoft/yii2/base/Module.php:427
#3 /home/projects/toma/toma-coreshop/vendor/yiisoft/yii2/base/Module.php:586
#4 /home/projects/toma/toma-coreshop/vendor/yiisoft/yii2/base/Module.php:522
#5 /home/projects/toma/toma-coreshop/vendor/yiisoft/yii2/web/Application.php:103
#6 /home/projects/toma/toma-coreshop/vendor/symfony/browser-kit/Client.php:351
#7 Codeception\Lib\InnerBrowser->amOnPage
#8 /home/projects/toma/toma-coreshop/backend/tests/_support/_generated/FunctionalTesterActions.php:526
#9 /home/projects/toma/toma-coreshop/backend/tests/functional/LoginCest.php:18
#10 backend\tests\functional\LoginCest->loginUser
Time: 251 ms, Memory: 16.00MB
There was 1 error:
---------
ERRORS!
Tests: 1, Assertions: 0, Errors: 1.
The errors flows one by one on every step whit those tests. My configuration file looks like (backend\codeception.yml):
namespace: backend\tests
actor: Tester
paths:
tests: tests
log: tests/_output
data: tests/_data
helpers: tests/_support
settings:
bootstrap: _bootstrap.php
colors: true
memory_limit: 1024M
modules:
config:
Yii2:
configFile: 'config/test.php'
In my test.php I have:
<?php
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/main.php'),
require(__DIR__ . '/main-local.php'),
[
'id' => 'app-backend-test',
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=coreshop',
'username' => '*****',
'password' => '*****',
'charset' => 'utf8',
//'enableSchemaCache' => true,
],
]
]
);
return $config;
And finally my LoginCest.php:
/**
* Class LoginCest
*/
class LoginCest
{
/**
* #param FunctionalTester $I
*/
public function loginUser(FunctionalTester $I)
{
$I->amOnPage('/admin/user/login');
$I->fillField('Username', '***');
$I->fillField('Password', '***');
$I->click('Вход');
}
}
I followed the instruction given on the codeception site for the Yii2-advanced template. I am trying to test on old project so it is not newly installed Yii2-advanced if that matters in this case. Thank you!
EDIT
Main.php:
$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',
'name' => 'Online Shop Admin',
'homeUrl' => '/admin',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'language' => 'bg-BG',
'bootstrap' => [
[
'class' => 'app\components\LanguageSelector',
'supportedLanguages' => [],
],
'log',
'devicedetect'
],
'modules' => [
'user' => [
'controllerMap' => [
'security' => 'backend\controllers\user\SecurityController',
'admin' => 'backend\controllers\user\AdminController',
],
'modelMap' => [
'User' => 'backend\models\User',
'SettingsForm' => 'backend\models\SettingsForm',
'Profile' => 'backend\models\Profile',
/*'UserSearch' => 'backend\models\UserSearch',*/
],
'rememberFor' => 1209600,
],
'statistics' => [
'class' => 'backend\modules\statistics\Module',
],
'catalogue' => [
'class' => 'backend\modules\catalogue\Module',
],
'news' => [
'class' => 'backend\modules\news\Module',
],
'sales' => [
'class' => 'backend\modules\sales\Module',
],
'wasteManagment' => [
'class' => 'backend\modules\wasteManagment\WasteManagment',
],
'help' => [
'class' => 'backend\modules\help\HelpInfo',
],
'marketing' => [
'class' => 'backend\modules\marketing\Module',
],
'translation' => [
'class' => 'backend\modules\translation\Module',
],
'gii' => [
'class' => 'yii\gii\Module',
'allowedIPs' => ['127.0.0.1', '::1', '192.168.33.1'], // adjust this to your needs
'generators' => [
'crud' => [
'class' => 'backend\templates\crud_v1\Generator',
'templates' => ['mycrud' => '#backend/templates/crud_v1/default']
],
'model' => [
'class' => 'backend\templates\model_v1\Generator',
'templates' => ['mymodel' => '#backend/templates/model_v1/default']
],
/*'crud' => [
'class' => 'backend\templates\crud_module_v1\Generator',
'templates' => ['mycrudmodule' => '#backend/templates/crud_module_v1/default']
],
'model' => [
'class' => 'backend\templates\model_module_v1\Generator',
'templates' => ['mymodelmodule' => '#backend/templates/model_module_v1/default']
],*/
],
],
],
'components' => [
'assetManager' => [
'bundles' => [
'yii\bootstrap\BootstrapAsset' => [
'css' => [],
],
'yii\bootstrap\BootstrapPluginAsset' => [
'js' => []
],
'yii\web\JqueryAsset' => [
'js' => []
],
'wbraganca\dynamicform\DynamicFormAsset' => [
'js' => [
'/admin/dist/js/yii2-dynamic-form.js'
]
],
],
],
'urlManagerBackend' => [
'class' => 'yii\web\urlManager',
'baseUrl' => (isset($_SERVER['HTTPS']) ? "https" : 'http') . "://toma-coreshop.webbuild.com/admin",
'enablePrettyUrl' => true,
'showScriptName' => false,
],
'request' => [
'baseUrl' => '/admin',
'cookieValidationKey' => 'sew4789vb7834tvnv78',
'csrfParam' => '_backendCSRF',
],
'user' => [
'identityClass' => 'backend\models\User',
'enableAutoLogin' => true,
'loginUrl' => [ 'user/login'],
'identityCookie' => [
'name' => '_backendUser', // unique for backend
]
],
/*'session' => [
'name' => '_backendSessionId',
'savePath' => __DIR__ . '/../runtime/sessions',
],*/
'view' => [
'theme' => [
'pathMap' => [
'#dektrium/user/views' => '#backend/views/user',
'#dektrium/rbac/views' => '#backend/views/rbac',
],
],
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
],
'translate' => [
'class' => 'backend\components\Translate'
],
'tabSettings' => [
'class' => 'backend\components\TabSettings'
],
'system' => [
'class' => 'backend\components\System'
],
'moneyConvertor' => [
'class' => 'backend\components\MoneyConvertor'
],
'moneyWords' => [
'class' => 'backend\components\MoneyWords'
],
'OutData' => [
'class' => 'backend\components\OutData'
],
'MakeURL' => [
'class' => 'backend\components\MakeURL'
],
'makeUrl' => [
'class' => 'frontend\components\MakeURL'
],
'image' => [
'class' => 'backend\components\Image'
],
'formatter' => [
'class' => 'yii\i18n\Formatter',
'nullDisplay' => '',
],
'devicedetect' => [
'class' => 'alexandernst\devicedetect\DeviceDetect'
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
'profile' => 'user/settings/profile',
],
],
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/messages',
'sourceLanguage' => 'bg',
'fileMap' => [
'app' => 'app.php',
],
],
'help*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/modules/help/messages',
'sourceLanguage' => 'bg',
'fileMap' => [
'help' => 'help.php',
],
],
'sales*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/modules/sales/messages',
'sourceLanguage' => 'bg',
'fileMap' => [
'catalogue' => 'sales.php',
],
],
'statistics*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/modules/statistics/messages',
'sourceLanguage' => 'bg',
'fileMap' => [
'catalogue' => 'statistics.php',
],
],
'catalogue*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/modules/catalogue/messages',
'sourceLanguage' => 'bg',
'fileMap' => [
'catalogue' => 'catalogue.php',
],
],
'marketing*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/modules/marketing/messages',
'sourceLanguage' => 'bg',
'fileMap' => [
'catalogue' => 'news.php',
],
],
'news*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/modules/news/messages',
'sourceLanguage' => 'bg',
'fileMap' => [
'catalogue' => 'news.php',
],
],
'message*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/modules/translation/messages',
'sourceLanguage' => 'bg',
'fileMap' => [
'message' => 'message.php',
],
],
'kvgrid*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/messages/kvgrid',
'sourceLanguage' => 'bg',
'fileMap' => [
'kvgrid' => 'kvgrid.php',
],
],
],
],
],
'params' => $params,
];
Main-local.php:
$config = [
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'ud_6581BcmdaOC-RoK4LznBhsD7W4pyU',
],
],
'container' => [
'definitions' => [
kartik\grid\GridView::class => [
'krajeeDialogSettings' => ['overrideYiiConfirm' => false],
'responsiveWrap' => false,
'bordered' => false,
'tableOptions' => [
'class' => 'table full-color-table full-dark-table hover-table',
],
'resizableColumns' => true,
'hover' => true,
'layout' => "{items}\n{summary}\n{pager}",
'rowOptions' => function ($model) {
if(!empty($model->id))
return ['data-id' => $model->id];
else
return;
},
],
],
],
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['modules']['debug']['allowedIPs'] = ['*'];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
$config['modules']['gii']['allowedIPs'] = ['*'];
}
return $config;

PendalF89/yii2-filemanager upload error. (Call to a member function saveAs() on null)

getting
Call to a member function saveAs() on null
error from ajax request while uploading image via filemanager.
Config:
...
'modules' => [
'site' => [
'class' => 'app\modules\site\Module',
],
'user' => [
'class' => 'app\modules\user\Module',
'controllerNamespace' => 'app\modules\user\controllers\frontend',
'viewPath' => '#app/modules/user/views/frontend',
],
'admin' => [
'class' => 'app\modules\admin\Module',
'layout' => '#app/views/layouts/admin',
'modules' => [
'user' => [
'class' => 'app\modules\user\Module',
'controllerNamespace' => 'app\modules\user\controllers\backend',
'viewPath' => '#app/modules/user/views/backend',
],
'pages' => [
'class' => 'bupy7\pages\Module',
'controllerNamespace' => 'bupy7\pages\controllers\backend',
'controllerMap' => [
'manager' => [
'class' => 'bupy7\pages\controllers\backend\ManagerController',
],
],
],
'gallery' => [
'class' => 'sadovojav\gallery\Module',
'basePath' => '#webroot/galleries',
],
'filemanager' => [
'class' => 'pendalf89\filemanager\Module',
// Upload routes
'routes' => [
// Base absolute path to web directory
'baseUrl' => '',
// Base web directory url
'basePath' => '#webroot',
// Path for uploaded files in web directory
'uploadPath' => 'uploads',
],
// Thumbnails info
'thumbs' => [
'small' => [
'name' => 'Small',
'size' => [100, 100],
],
'medium' => [
'name' => 'Medium',
'size' => [300, 200],
],
'large' => [
'name' => 'Big',
'size' => [500, 400],
],
],
],
],
],
...
actionUpload() in Controller
public function actionUpload()
{
$model = new Mediafile();
$routes = $this->module->routes;
$rename = $this->module->rename;
$model->saveUploadedFile($routes, $rename);
Yii::$app->response->format = Response::FORMAT_JSON;
$tagIds = Yii::$app->request->post('tagIds');
if ($tagIds !== 'undefined') {
$model->setTagIds(explode(',', $tagIds));
}
$bundle = FilemanagerAsset::register($this->view);
if ($model->isImage()) {
$model->createThumbs($routes, $this->module->thumbs);
}
$response['files'][] = [
'url' => $model->url,
'thumbnailUrl' => $model->getDefaultThumbUrl($bundle->baseUrl),
'name' => $model->filename,
'type' => $model->type,
'size' => $model->file->size,
'deleteUrl' => Url::to(['file/delete', 'id' => $model->id]),
'deleteType' => 'POST',
];
return $response;
}
Checked in the model,
$this->file = UploadedFile::getInstance($this, 'file');
in saveUploadedFile() returns null instead of object.
The problem is that the function saveUploadedFile() is been executed, the file is saved and the record is created in the database, but it returns error.

application configuration file path of yii2

I installed yii2 and then added gii to yii2 from this link.
return [
'bootstrap' => ['gii'],
'modules' => [
'gii' => 'yii\gii\Module',
// ...
],
// ...
];
I want to plce this code in application configuration file where it is located?
Application configuration file reside in: project_name/config/web.php
if (YII_ENV_DEV) {
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class'=>'yii\gii\Module',
'allowedIPs'=>['127.0.0.1','192.168.1.*'],
];
You will find a file web.php which is in in the config folder located at your root app folder, the file will contain something like the following:
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$config = [
'id' => 'basic',
'name' => 'My Cool App',//If this line exists change it to your new app name otherwise add it.
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'#bower' => '#vendor/bower-asset',
'#npm' => '#vendor/npm-asset',
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '_4wmrZYaMY7joBAFHrXKpEIFvs9m9S_I',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
],
'params' => $params,
];
if(YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
}
return $config;
Notice I've added a line: 'name' => 'My Cool App',
Hope this helps.

Yii2 kartik typeahead - get number of suggestions

I'm using kartik's typeahead widget for Yii2 in a view:
echo \kartik\typeahead\Typeahead::widget([
'name' => 'serial_product',
'options' => [
'placeholder' => 'Filter as you type ...',
'autofocus' => "autofocus"
],
'scrollable' => TRUE,
'pluginOptions' => [
'highlight' => TRUE,
'minLength' => 3
],
'dataset' => [
[
'remote' => Url::to(['transfers/ajaxgetinventoryitemsnew']) . '?search=%QUERY',
'limit' => 10
]
],
'pluginEvents' => [
"typeahead:selected" => "function(obj, item) { add_item(item.id); return false;}",
],
]);
How can i get the number of loaded suggestions after the remote dataset is retrieved to execute a javascript function like:
displaynumber(NUMBEROFSUGGESTIONS);
After checking through the source of kartiks widget i came up with the following solution:
echo \kartik\typeahead\Typeahead::widget([
'name' => 'serial_product',
'options' => [
'placeholder' => 'Filter as you type ...',
'autofocus' => "autofocus",
'id' => 'serial_product'
],
'scrollable' => TRUE,
'pluginOptions' => [
'highlight' => TRUE,
'minLength' => 3
],
'dataset' => [
[
'remote' => [
'url' => Url::to(['transfers/ajaxgetinventoryitemsnew']) . '?search=%QUERY',
'ajax' => ['complete' => new JsExpression("function(response)
{
jQuery('#serial_product').removeClass('loading');
checkresult(response.responseText);
}")]
],
'limit' => 10
]
],
'pluginEvents' => [
"typeahead:selected" => "function(obj, item) { checkresult2(item); return false;}",
],
]);
where response.responseText is containing the response from server (json).
function checkresult(response) {
var arr = $.parseJSON(response);
console.log(arr.length);
}
With this function i can get then count of suggestions delivered from server.