Monolog MongoDBHandler having BindingResolutionException error in Laravel 8 - php

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'
]
));
}
// ...

Related

Laravel log file specific to a package

I'm writing a couple of laravel packages and I'm wondering if it is possible to have the package write to a specific log file but only for messages related to the package?
I tried making a logging.php file in the packages/myorg/mypackage/config (below) but it doesn't seem to do anything.
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
return [
'default' => env('LOG_CHANNEL', 'stack'),
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/mypackage.log'),
'level' => env('LOG_LEVEL', 'debug'),
]
]
];
I am using "jeroen-g/laravel-packager" to set up the packages. It appears to manually load the mypackage.config in the ServiceProvider bootForConsole
protected function bootForConsole(): void
{
// Publishing the configuration file.
$this->publishes([
mypackage.'/../config/mypackage.php' => config_path('mypackage.php'),
], 'mypackage.config');
}
I'm not sure how to add custom logging to that though. I'm still learning Laravel and I'm not quite sure what or how the main applications config/logging.php is read so I'm not quite sure how to inject a custom version for an add-on package.
EDIT:
I found a post that suggested using the following in the ServiceManager boot() method:
$this->app->make('config')->set('logging.channels.mychannel', [
/* settings */
]);
I used the package config to set a 'logging' => [ 'channels' => [ 'mychannel' => [ /* settings */ ] ] ] and could then do the same thing as above with:
$this->app->make('config')->set('logging.channels.mychannel', config('mypackage.logging.channels.mychannel');
But that still required something in the code. The next best thing I have found thus far is to change my config/logging.php to config/logging.channels.php and include something like:
return [
'mychannel' => [
'driver' => 'single',
'path' => storage_path('logs/mypackage.log'),
'level' => env('LOG_LEVEL', 'debug'),
]
];
Then in the service provider register() method add:
$this->mergeConfigFrom(__DIR__ . '/../config/logging.channels.php', 'logging.channels');
I tried doing it from the original 'logging.php' with channels array nested in a 'logging' key, but array_merge doesn't appear to merge the nested elements so my channel never showed up in logging.channels.
I'm not sure if this is ideal, however. I'd still like to know if there is a 'better' or best practices way of adding custom package logging parameters and whether there is a need to publish it in any way (and how).

The "access_key" option must be provided to use fixer.io

For the currency conversion i am using "florianv/laravel-swap": "^1.1" library. Florianv/Laravel-swap.
As Fixer.io has changed its implementation, it is necessary to pass the access_key with the request, and because of that i am getting this error: "InvalidArgumentException: The "access_key" option must be provided to use fixer.io in /var/www/project/project-files/vendor/florianv/exchanger/src/Service/Fixer.php:51".
I registered and got the access_key.
I updated the library using composer and now i can see three constants in the vendor/florianv/exchanger/src/Service/Fixer.php.
const ACCESS_KEY_OPTION = 'access_key';
const LATEST_URL = 'http://data.fixer.io/api/latest?base=%s&access_key=%s';
const HISTORICAL_URL = 'http://data.fixer.io/api/%s?base=%s&access_key=%s';
To pass the access key i tried this:
I have a swap.php in config folder which looks something like this:
return [
'options' => [
'cache_ttl' => 86400, // 24 hours.
'cache_key_prefix' => 'currency_rate'
],
'services' => [
'fixer' => true,
],
'currency_layer' => [
'access_key' => 'asdfas7832mw3nsdfa776as8dfa', // Your app id
'enterprise' => true, // True if your AppId is an enterprise one
],
'cache' => env('CACHE_DRIVER', 'file'),
'http_client' => null,
'request_factory' => null,
'cache_item_pool' => null,
];
This had one more option which was commented, i enabled and passed the access_key in it but it doesn't work.
I also added it in services block below 'fixer => true'.
'currency_layer' => [
'access_key' => 'asdfas7832mw3nsdfa776as8dfa'
]
Also in options block:
'options' => [
'cache_ttl' => 86400, // 24 hours.
'cache_key_prefix' => 'currency_rate',
'access_key'=>'7ca208e9136c5e140d6a14427bf9ed21'
],
I tried with adding access_key in config/services.php file but it also didn't work.
'fixer' => [
'access_key' => 'asdfas7832mw3nsdfa776as8dfa'
],
Even i tried, adding to env file and calling from there, but no success. How do i pass the access_key, can anyone help me on this, what should be the approach.
vendor/florianv/exchanger/src/Service/Fixer.php -> don't touch the constant (that was my own error).
Pass the options-array by creating the Builder:
$options = ['access_key' => 'YourGeneratedAPIKeyAtCurrencyLayer'];
$this->exchangeSwap = (new Builder($options))
->add('fixer', $options )
->build();
I hope I could help ;-)

ZF2 Zend Logger - Filters by priority

I'm using the Zend Logger with following configuration in the module_config.php:
'log' => [
\Base\Log\ConsoleLoggerAwareInterface::class => [
'writers' => [
'standard-output' => [
'name' => 'stream',
'options' => [
'stream' => 'php://output',
],
],
],
],
]
But as it is I can't influence the log to filter or suppress messages.
The goal is to improve the logging to be smarter.
I think I need to add a filter to the writer but I can't find an example how to do that in the module_config.php.
Is there also a way to call a script (e.g. from within a cron) by using a verbosity level?
I hope you know what I'm trying to achive.
Edit:
I have this example in my code:
$this->consoleLogger->emerg('EMERG');
$this->consoleLogger->alert('ALERT');
$this->consoleLogger->crit('CRIT');
$this->consoleLogger->err('ERR');
$this->consoleLogger->warn('WARN');
$this->consoleLogger->notice('NOTICE');
$this->consoleLogger->info('INFO');
$this->consoleLogger->debug('DEBUG');
Should it then not output the filtered ones?
Q: How to filter a Log Writer to a specific error level?
Add a filters key to the particular writer's configuration. Here's direct instantiation to remove any configuration peculiarities: this outputs only "WARN" and "EMERG" messages:
$config = [
'writers' => [
'standard-output' => [
'name' => 'stream',
'options' => [
'stream' => 'php://output',
'filters' => \Zend\Log\Logger::WARN,
],
],
],
];
$logger = new \Zend\Log\Logger($config);
$logger->emerg('EMERG');
$logger->warn('WARN');
$logger->debug('DEBUG');
Adding the filters configuration to your modules_config.php should have a similar effect. If not, check your zend-log version (with eg composer show) and advise.
Q: How to change error level filter with the -v command line parameter?
AFAIK, there is no automatic way to bind the standard verbose flag (-v) with a particular logging level. So you'll have to write your own filter. One thing that's neat to know is that the filters key can take:
an int (as done above, which translates to the built-in log level);
a string (corresponding to a class name implementing \Zend\Log\Filter\FilterInterface);
an object (instance of \Zend\Log\Filter\FilterInterface);
or an array of these.
You can use this flexibility to solve your need of binding a command line parameter to a log value. Here is a custom class that shows emergency events by default, but for every v on the command line increases the shown priority:
class CliLoggingFilter implements \Zend\Log\Filter\FilterInterface
{
public function __construct()
{
$this->level = \Zend\Log\Logger::EMERG;
if (array_key_exists('v', $args = getopt('v'))) {
$this->level += count($args['v']);
}
}
public function filter(array $event)
{
return ($event['priority'] <= $this->level);
}
}
You'd then have a configuration like: 'filters' => CliLoggingFilter::class.
$ php public/index.php
2016-07-25T10:57:28-04:00 EMERG (0): EMERG
$ php public/index.php -vvvv
2016-07-25T10:57:32-04:00 EMERG (0): EMERG
2016-07-25T10:57:32-04:00 WARN (4): WARN
$ php public/index.php -vvvvvvv
2016-07-25T10:57:34-04:00 EMERG (0): EMERG
2016-07-25T10:57:34-04:00 WARN (4): WARN
2016-07-25T10:57:34-04:00 DEBUG (7): DEBUG
Q: How to change all routes to use -v?
AFAIK, there is no way to specify a global command line parameter. You need to either (a) update all your console routes to accept the argument or (b) pass the log level a different way.
Updating all your routes isn't terribly hard. You can define a variable that holds the value and then include that in the configuration, like so:
$globalConsoleRouteParams = '[--verbose|-v]';
return [ 'console' => 'router' => 'routes' => [
'foo' => [ 'options' => [ 'route' => "foo $globalConsoleRouteParams ..." ] ],
'bar' => [ 'options' => [ 'route' => "bar $globalConsoleRouteParams ..." ] ],
// ...
]];
Alternatively, you could use say environment variables to pass your desired log level, plus perhaps any additional configuration you might desire. Modifying our earlier example:
class CliLoggingFilter implements \Zend\Log\Filter\FilterInterface
{
public function __construct()
{
$this->level = \Zend\Log\Logger::EMERG;
if (false !== ($level = getenv('LOG_LEVEL'))) {
$this->level = $level;
}
}
// ...
}
Then it may be invoked like
$ LOG_LEVEL=7 php index.php foo

Setting/retrieving mode in Slim Framework V3

I am new to Slim Framework (PHP). I was going through tutorials and testing some code and tried the following:
$app=new App([
'mode'=>file_get_contents(INC_ROOT . '/mode.php')
]);
echo $app->config('mode');
The output was blank.
It seems the function config() works with V2, however I am using V3. What am I doing wrong?
Slim 3 no longer has a config method. Instead, you must add configuration settings through the dependency injection container:
$app = new \Slim\App([
'settings' => [
'mode' => true
]
]);
$container = $app->getContainer();
echo $container->get('settings')['mode'];
A few things worth noting:
Slim 3 no longer handles managing different versions of configuration settings through a mode setting. So, you can set a value for a setting variable called mode as I've demonstrated here, but it won't actually do anything (i.e., Slim won't use it to determine your environment).
As an alternative, you can check out userfrosting/Config, a library we've been working on that can search multiple directories and different environment configuration files, merging together their contents:
/path/to/config/default.php
return [
'contacts' => [
'housekeeper' => [
'name' => 'Alex',
'email' => 'alex#cleansthetoilet.com'
]
]
];
/path/to/config/production.php
return [
'contacts' => [
'housekeeper' => [
'email' => 'alex#istheboss.com'
]
],
'database' => [
'password' => 'sup3rC-cr3t'
]
];
index.php
$app = new \Slim\App();
$container = $app->getContainer();
// Site config object (separate from Slim settings)
$container['config'] = function ($c) {
// Create and inject new config item
$config = new \UserFrosting\Config\Config();
$config->setPaths([
'/path/to/config'
]);
$config->loadConfigurationFiles('production');
return $config;
};
This will recursively merge in the settings from development.php with those in default.php, updating settings with the same name and scope as necessary:
Running print_r($container['config']); returns:
[
'contacts' => [
'housekeeper' => [
'name' => 'Alex',
'email' => 'alex#istheboss.com'
]
],
'database' => [
'password' => 'sup3rC-cr3t'
]
]
Notice that the value of contacts.housekeeper.email has been updated to 'alex#istheboss.com', and that the database config info has been merged in. Incidentally, you can also access config settings using the more convenient "dot syntax":
$config = $container->get('config');
echo $config['contacts.housekeeper.email'];
// Easier to type instead of $config['contacts']['housekeeper']['email'];
We recommend injecting this as a separate config service in Slim, rather than using their settings array.
You can combine this with phpdotenv to load settings from your system environment, or any .env files you create:
/path/to/config/production.php
return [
'database' => [
'password' => getenv('DB_PASSWORD')
]
];

ZF2 2.2.6 -> 2.3.0 causes DI to try to instantiate `Zend\I18n\Translator\TranslatorInterface` instead of `Zend\I18n\Translator\Translator`

EDIT: Yup, is bug.
I suspect this is a bug, so I've submitted it as an issue at https://github.com/zendframework/zf2/issues/6051, but just in case it's just me being stupid it doesn't hurt to ask here as well. :)
After upgrading ZF2 from 2.2.6 to 2.3.0 I'm receiving the following series of uncaught exceptions inside Zend\Di\Di:
Zend\Di\Exception\RuntimeException: Invalid instantiator of type "NULL" for "Zend\I18n\Translator\TranslatorInterface". in /path/to/vendor/zendframework/zendframework/library/Zend/Di/Di.php on line 305
Zend\ServiceManager\Exception\ServiceNotCreatedException: An exception was raised while creating "Zend\I18n\Translator\TranslatorInterface"; no instance returned in /path/to/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php on line 909
Zend\ServiceManager\Exception\ServiceNotCreatedException: An abstract factory could not create an instance of zendi18ntranslatortranslatorinterface(alias: Zend\I18n\Translator\TranslatorInterface). in /path/to/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php on line 1070
Zend\ServiceManager\Exception\ServiceNotCreatedException: An exception was raised while creating "MvcTranslator"; no instance returned in /path/to/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php on line 909
Unfortunately, I can't work out why exactly this is happening, but the I18n module worked fine prior to the upgrade. I have the i18n extension installed and loaded correctly.
I have this in module/Application/config/module.config.php
'service_manager' => [
'aliases' => [
'translator' => 'MvcTranslator',
],
],
and this in each module's module.config.php
'translator' => [
'translation_file_patterns' => [
[
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
],
],
],
The only DI configuration I have so far is this:
'di' => [
'instance' => [
'Zend\View\HelperLoader' => [
'parameters' => [
'map' => [
'zfcUserIdentity' => 'ZfcUser\View\Helper\ZfcUserIdentity',
'zfcUserLoginWidget' => 'ZfcUser\View\Helper\ZfcUserLoginWidget',
],
],
],
],
],
Does 2.3.0 add a requirement to add additional configuration to the DI block in order for I18n to work properly? This isn't reflected in the documentation and I haven't been able to work it out from reading the code so far, but from the exceptions that are being thrown it looks like it's actually trying to create an instance of Zend\I18n\Translator\TranslatorInterface itself rather than Zend\I18n\Translator\Translator as it did previously?
Anyone got any ideas?
Answer found on https://github.com/zendframework/zf2/pull/5959:
In DiAbstractServiceFactory, the following function needs to be changed from:
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
return $this->instanceManager->hasSharedInstance($requestedName)
|| $this->instanceManager->hasAlias($requestedName)
|| $this->instanceManager->hasConfig($requestedName)
|| $this->instanceManager->hasTypePreferences($requestedName)
|| $this->definitions->hasClass($requestedName);
}
to:
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
if ($this->instanceManager->hasSharedInstance($requestedName)
|| $this->instanceManager->hasAlias($requestedName)
|| $this->instanceManager->hasConfig($requestedName)
|| $this->instanceManager->hasTypePreferences($requestedName)
) {
return true;
}
if (! $this->definitions->hasClass($requestedName) || interface_exists($requestedName)) {
return false;
}
return true;
}
I believe this has been / is being pull-requested, so it should be included in the next update to ZF2.3.

Categories