Yii log skip 404 errors - php

Maybe exist solution to skip 404 exceptions ? I'mean not store this messages in log file ?
2015/04/09 12:28:52 [error] [exception.CHttpException.404] exception 'CHttpException' with message 'Невозможно обработать запрос "offer/downloadOffer".' in /var/www/yii/framework/web/CWebApplication.php:286
Stack trace:
#0 /var/www/yii/framework/web/CWebApplication.php(141): CWebApplication->runController('offer/downloadO...')
#1 /var/www/yii/framework/base/CApplication.php(184): CWebApplication->processRequest()
#2 /var/www/LAP/www/index.php(16): CApplication->run()
#3 {main}
REQUEST_URI=/offer/downloadOffer

For Yii 2.0, you can make your config/main.php like this:
return [
'components' => [
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
'except' => ['yii\web\HttpException:404'],
],
],
],
],
];

For Yii 1.1, the correct way to exclude a category is to use the except key. Prepending a ! in the categories key as per the accepted answer will actually result in only matching categories that start with a !. So whilst it might appear to work, you're actually going to be suppressing all categories. See the filterAllCategories() function of the source code - there's no processing of the ! character, only for the * wildcard: GitHub Source.
I tried the !exception.CHttpException.404 approach in the accepted answer and thought I'd solved the issue of hiding the 404 errors, but then I realised after much hair pulling that this was resulted in no logs being logged!
The correct syntax to ignore a category is:
array(
'class' => 'CFileLogRoute',
'except' => 'exception.CHttpException.404'
)

Solution is exclude categories.
array(
'class' => 'CFileLogRoute',
'categories' => '!exception.CHttpException.404'
),
array(
'class' => 'CEmailLogRoute',
'categories' => '!exception.CHttpException.*'
),

Related

Select2 keep showing "Searching" in ajax with pivot (n-n) in Laravel Backpack 5 Pro

I have 2 models: Order and Product, each has belongsToMany with pivot set properly.
In OrderCrudController, I also use FetchOperation and make a fethProducts() function as below:
use \Backpack\CRUD\app\Http\Controllers\Operations\FetchOperation;
public function fetchProducts()
{
return $this->fetch([
'model' => \App\Models\Product::class,
'searchable_attributes' => ['name','sku']
]);
// return $this->fetch(\App\Models\Product::class); <-- I also tried this one
}
protected function setupCreateOperation()
{
CRUD::setValidation(OrderRequest::class);
// other fields
$this->crud->addField([
'name' => 'products',
'type' => 'relationship',
'pivotSelect' => [
'attribute' => 'name',
'ajax' => true,
],
'subfields' => [
[
'name' => 'quantity',
'type' => 'number',
],
],
]);
}
But it comes to unexpected behavior when I search the product, the select2 field remains "searching" though the request successfully retrieved the data.
screenshot - select2 field
screenshot - ajax results
PS: this field works perfectly without subfields, no vendor overrides etc., so I think I've set everything correctly.
Anyone can help?
This was asked two months ago but somehow I missed it, just noticed it today after someone opened an issue on the GitHub repository.
I am happy you guys found a solution for it but unfortunatelly I cannot recommend it as using the select2_from_ajax will miss the functionality to don't allow the selection of the same pivots twice, otherwise you will have undesired consequences when saving the entry.
I've just submitted a PR to fix this issue, I will ping you guys here when it's merged, probably by next Monday.
Cheers
I just came accross this exact problem and after quite some research and trials, i finally found a solution !
The problem seems to be related to the relationship field type inside the pivotSelect. Try to use select2_from_ajax instead and don't forget to set method to POST explicitly, that worked for me like a charm.
Here is what you might try in your case :
$this->crud->addField([
'name' => 'products',
'type' => 'relationship',
'pivotSelect' => [
'attribute' => 'name',
'type' => 'select2_from_ajax',
'method' => 'POST',
'data_source' => backpack_url('order/fetch/products') // Assuming this is the URL of the fetch operation
],
'subfields' => [
[
'name' => 'quantity',
'type' => 'number',
],
],
]);

Monolog MongoDBHandler having BindingResolutionException error in Laravel 8

I tried to create a mongodb logging channel
'mongo' => [
'driver' => 'monolog',
'handler' => \Monolog\Handler\MongoDBHandler::class,
'formatter' => \Monolog\Formatter\MongoDBFormatter::class,
'handler_with' => [
'mongo' => new \MongoDB\Client("mongodb://localhost:27017"),
'database' => 'testdb',
'collection' => 'testcoll'
]
],
However, im getting error:
Illuminate\Contracts\Container\BindingResolutionException(code: 0): Unresolvable dependency resolving [Parameter #0 [ <required> $mongodb ]] in class Monolog\Handler\MongoDBHandler
The error is only resolved when I tried to add type hint to the class constructor but obviously I can't do that since it's a package:
public function __construct(Client<<if I add this it works>> $mongodb, string $database, string $collection, $level = Logger::DEBUG, bool $bubble = true)
Any solution for this?
So, I wanted to add here a complete answer because this post is the first one that shows up when looking for adding a mongo logger, and since the answer is buried in the comments, I wanted to add a proper answer.
The solution was to change the key mongo to mongodb in the handler_with array.
Leaving the working code like this:
'mongo' => [
'driver' => 'monolog',
'handler' => \Monolog\Handler\MongoDBHandler::class,
'formatter' => \Monolog\Formatter\MongoDBFormatter::class,
'handler_with' => [
'mongodb' => new \MongoDB\Client("mongodb://localhost:27017"),
'database' => 'testdb',
'collection' => 'testcoll'
]
],
Also, you could add the following element at the same level as formatter to set a custom max level of nesting. This is because, by default, the document stored cannot have a depth greater than 3, and it's automatically converted to "[...]" in the log.
'formatter_with' => [
'maxNestingLevel' => 10
],
Warning, in the probable event of a recursion, or an incredibly deep array, it can cause problems in mongo, because it doesn't support more than 100 levels of nesting, source.
According to the Laravel 8.x doc:
'mongo' => [
'driver' => 'monolog',
'handler' => \Monolog\Handler\MongoDBHandler::class,
'formatter' => \Monolog\Formatter\MongoDBFormatter::class,
'with' => [ // <-- This is `with` instead of `handler_with`
// 'mongodb' => new \MongoDB\Client("mongodb://localhost:27017"), <-- This line will cause an error in `php artisan config:cache`
'database' => 'testdb',
'collection' => 'testcoll'
],
],
So you need to configure the service for MongoDBHandler. as you mentioned with a look at the handler source code the first argument is $mongodb.
public function __construct($mongodb, string $database, string $collection, $level = Logger::DEBUG, bool $bubble = true)
and to be able to resolve this dependency we can configure service container:
// AppServiceProvider.php
// ...
public function register() {
$this->app->when(\Monolog\Handler\MongoDBHandler::class)
->needs('$mongodb')
->give(app(
\MongoDB\Client::class,
[
'uri' => 'mongodb://localhost:27017'
]
));
}
// ...

Yii2 Debugbar is not showing the file line

I am trying to see the traceLine on Yii2 debug bar like explains in (https://github.com/yiisoft/yii2-debug#open-files-in-ide), but I can't see it.
I have Yii2 2.0.28 and debug-bar 2.1.9 with php 7.2.19
For example: is there any way, inspecting any debug bar’s panel, to know which line of my code thrown a trace/profile action in the debug bar?
Or how can I see where is located any query I am seeing in the database panel?
My config:
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
'traceLine' => '{file}:{line}',
'allowedIPs' => ['*'],
'panels' => [
'db' => [
'class' => 'yii\debug\panels\DbPanel',
'defaultOrder' => [
'seq' => SORT_ASC
],
'defaultFilter' => [
'type' => 'SELECT'
]
],
],
];
There are two properties in configuration that affect how the files are displayed in logs in debug bar.
1) traceLine property of debug module. This property contains a template for displaying single line of trace.
In configuration it may look like this
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
'traceLine' => '{file}:{line}',
// ... other debug module configurations
]
2) traceLevel property of log component. This affect how many calls will be displayed in trace. The calls of framework's classes are not displayed in debug toolbar, only your files are displayed.
The configuration might look like this
'components' => [
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
// ... other log component configurations
],
// ... other components
],
In the example the traceLevel depends on YII_DEBUG constant. This is used to avoid performance issues in production environments. This is also how traceLevel is set in default yii2 application templates.
The YII_DEBUG constant is usually set in index.php file like this
defined('YII_DEBUG') or define('YII_DEBUG', true);

How use full text TNTSearch facade

I tried TNTSearch, but the results are only for the complete words. For example, the phrase Facilis dolorem gives me all combinations of records with the word facilis or word dolorem.
How can I do to the search with TNTSearch in Laravel?
LIKE %lore%
If I type lore, I don't get the records that have the word lore in the middle.
You should enable fuzzy search via config like mentioned in the docs:
'tntsearch' => [
'storage' => storage_path(), //place where the index files will be stored
'fuzziness' => env('TNTSEARCH_FUZZINESS', false),
'fuzzy' => [
'prefix_length' => 2,
'max_expansions' => 50,
'distance' => 2
],
],
ie. if this is your config set you variable TNTSEARCH_FUZZINESS in .env to true and you should get the results you expect.
Also, if you already have indexes created which seems like you do you'll have to reindex the content in order for fuzzines to kick in...
mine same issue not solved and finally used other good alternate:
laravel-scout-mysql-driver
try it
but exactly answer for your question:
you must use *lore* in your query. more documentation for queries:
Boolean Full-Text Searches
I had this issue and solved it via add 'asYouType' => false, in config\scout.php.
my code is :
'tntsearch' => [
'storage' => storage_path(), //place where the index files will be stored
'fuzziness' => true,
'fuzzy' => [
'prefix_length' => 2,
'max_expansions' => 50,
'distance' => 2
],
'asYouType' => false,
],

Cant resolve site/index after splitting in two "modules"

I wanted to split manager and frontend:
root/manager/controllers/SiteController.php
namespace manager\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
class SiteController extends Controller
{
public function actionIndex()
{
echo 'hallo';
//return $this->render('index');
}
}
root/manager/config/web.php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'manager\controllers',
'bootstrap' => ['log'],
'modules' => [
'manager' => [
'class' => 'manager\Module',
],
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'X',
],
'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.
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'' => 'site/index',
'fragebogen/erstellung/<id>' => 'questionary/creation',
'fragebogen/erstellung' => 'questionary/creation',
'auftraege-importieren' => 'upload/jobs',
'auftraege-erfolgreich-importiert' => 'upload/jobssuccess',
],
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module';
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = 'yii\gii\Module';
}
return $config;
root/manager/web/index.php
<?php
// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/../../vendor/autoload.php');
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
$config = require(__DIR__ . '/../config/web.php');
(new yii\web\Application($config))->run();
And i get this error:
exception 'yii\base\InvalidRouteException' with message 'Unable to resolve the request "site/error".' in /kunden/xxx/xxx/vendor/yiisoft/yii2/base/Module.php:461 Stack trace:
#0 /kunden/xxx/xxx/vendor/yiisoft/yii2/web/ErrorHandler.php(80): yii\base\Module->runAction('site/error')
#1 /kunden/xxx/xxx/vendor/yiisoft/yii2/base/ErrorHandler.php(95): yii\web\ErrorHandler->renderException(Object(yii\web\NotFoundHttpException))
#2 [internal function]: yii\base\ErrorHandler->handleException(Object(yii\web\NotFoundHttpException))
#3 {main} Previous exception: exception 'yii\base\InvalidRouteException' with message 'Unable to resolve the request "site/index".' in /kunden/xxx/xxx/vendor/yiisoft/yii2/base/Module.php:461 Stack trace:
#0 /kunden/xxx/xxx/vendor/yiisoft/yii2/web/Application.php(83): yii\base\Module->runAction('site/index', Array)
#1 /kunden/xxx/xxx/vendor/yiisoft/yii2/base/Application.php(375): yii\web\Application->handleRequest(Object(yii\web\Request))
#2 /kunden/xxx/xxx/manager/web/index.php(12): yii\base\Application->run()
#3 {main}
Next exception 'yii\web\NotFoundHttpException' with message 'Unable to resolve the request "site/index".' in /kunden/xxx/xxx/vendor/yiisoft/yii2/web/Application.php:95 Stack trace:
#0 /kunden/xxx/xxx/vendor/yiisoft/yii2/base/Application.php(375): yii\web\Application->handleRequest(Object(yii\web\Request))
#1 /kunden/xxx/xxx/manager/web/index.php(12): yii\base\Application->run()
#2 {main}
is this topic resolved?
If not, check your bootstrap file in common/config/bootstrap.php.
If your application is trying to use a path alias and it can't be resolved you will get the following exception!
exception 'yii\base\InvalidRouteException' with message 'Unable to resolve the request "site/error".
Example
wrong path is
Yii::setAlias('backend', dirname(dirname(DIR)) . 'backend');
correct path is
Yii::setAlias('backend', dirname(dirname(DIR)) . '/backend');
I think controllerNamespace may be deprectated in Yii2?
Can you replace that in your config, and use a controllerMap?
'controllerMap' => [
'site' => 'manager\controllers\SiteController',
],
Try removing the url rules, you might have to define the default rule to include the module name of at least. See this Custom URL rules with modules in Yii2
EDIT
Take a look at my installations instructions for my module https://github.com/Mihai-P/yii2-core
In short, not sure what controllerNamespace does there, you should remove it. I do something similar here: https://github.com/Mihai-P/yii2-core/blob/master/Module.php
Afterwards this
'class' => 'manager\Module'
I do not think that will work, where is the manager namespace? How would Yii know to look for it? I use composer to add the namespace in the autoloader, you should probably do something like that manually. Tell Yii that manager means your manager folder, afterwards it will find the controllers.
Also this might help, creating an alias to that folder https://github.com/Mihai-P/yii2-core#note-2
There are some config settings which look questionable to me, first
'modules' => [
'manager' => [
'class' => 'manager\Module',
],
],
Since you've created a separate app, you should remove this setting. From your screenshot there
are also no modules in the manager application.
For debugging, just set enablePrettyUrl URL to false and reeable it after it is working without
nice URLs.
You may also need set an alias in bootstrap.php for manager, not sure about that, but worth a try.
From your error message I'd say that the application is not able to load the SiteController at all,
because site/error fails also.
Addon: Personally, I'd recommend just one app per project, but I know that this a controversial topic.
It just looked to me, like you had that and were switching to two apps for some reason. If you just want to
apply a custom theme to your manager, you could easily do that by module configuration
...
I guess you dont have an alias to your application folder. Maybe autoloading component cannot find your controller file. You can add an alias in your config file doing:
\Yii::setAlias(’#manager’, dirname(__FILE__).'/..');
But I think the best way is to create another module for manager instead of dividing into different namespaces.
I have observed that this error generally occurs due to mis-configuration or due to case sensitive names of classes and namespaces. In my case the error was due to the configuration of ii8n component. I was using the following configuration
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/messages',
'sourceLanguage' => 'en-US',
'forceTranslation'=> true,
],
],
],
The issue was resolved after I removed the configuration
I guess you dont have an alias to manager folder.
add an alias in your common\config\bootstrap.php.
Yii::setAlias('#manager', dirname(dirname(__DIR__)) . '/manager');
so your common\config\bootstrap.php file should look like:
Yii::setAlias('#common', dirname(__DIR__));
Yii::setAlias('#frontend', dirname(dirname(__DIR__)) . '/frontend');
Yii::setAlias('#backend', dirname(dirname(__DIR__)) . '/backend');
Yii::setAlias('#console', dirname(dirname(__DIR__)) . '/console');
Yii::setAlias('#manager', dirname(dirname(__DIR__)) . '/manager');

Categories