How to create and use a custom daily log file in Laravel? - php

In Laravel I'm defining a custom log file in /config/logger.php:
'mycustomlog' => [
'driver' => 'stack',
'path' => storage_path('logs/mycustomlog.log'),
'level' => 'info',
],
Here's my stack driver for context:
'stack' => [
'driver' => 'stack',
'channels' => ['daily', 'syslog'],
'ignore_exceptions' => false,
],
and I'm calling it as follows:
Log::channel('mycustomlog')->info($e);
What I expect to happen:
A (daily) log file is created and the exception is logged. I.e mycustomlog-2019-11-07.log
What actually happens:
No log file is created, but the following error is logged to laravel.log:
[2019-11-07 10:25:31] laravel.EMERGENCY: Unable to create configured logger. Using emergency logger. {"exception":"[object] (ErrorException(code: 0): Undefined index: channels at /var/www/vendor/laravel/framework/src/Illuminate/Log/LogManager.php:232)
SOLUTION:
'mycustomlog' => [
'driver' => 'daily',
'channels' => ['syslog'],
'path' => storage_path('logs/mycustomlog.log'),
'level' => 'info',
],

You will need to have channels in the config logger.php see here. The point of the stack driver is to report to multiple channels.
'mycustomlog' => [
'driver' => 'stack',
'channels' => ['daily'],
'path' => storage_path('logs/mycustomlog.log'),
'level' => 'info',
],

If you don't want it to be in the stack you can have your config to point to the single driver like this
'mycustomlog' => [
'driver' => 'single',
'path' => storage_path('logs/mycustomlog.log'),
'level' => 'info',
]
Then call it the same way you tried on your own.
Log::channel('mycustomlog')->info($e);

Related

Rollbar is not seen by Laravel 8.0

I have installed the Rollbar 7.0 into Laravel 8.0. PHP version is 7.4
I am trying to send a test exception message using a simple Console command but that sends me nothing.
My configs are the following:
config/app.php:
return [
'providers' => [
Rollbar\Laravel\RollbarServiceProvider::class
...
]
config/logging.php:
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['other', 'rollbar'],
'ignore_exceptions' => false,
],
'rollbar' => [
'driver' => 'monolog',
'handler' => MonologHandler::class,
'access_token' => env('ROLLBAR_TOKEN'),
'level' => env('ROLLBAR_LEVEL'),
'enabled' => true,
'environment' => env('ROLLBAR_ENVIRONMENT'),
]
....
config/services.php (but seems to be that it doesn't work)
'rollbar' => [
'access_token' => env('ROLLBAR_TOKEN'),
'environment' => env('ROLLBAR_ENVIRONMENT'),
'level' => env('ROLLBAR_LEVEL')
],
app.env:
ROLLBAR_TOKEN=real_token
ROLLBAR_LEVEL=debug
ROLLBAR_ENVIRONMENT=backend_test
And the console command itself has the following view:
public function handle()
{
// Rollbar::init([
// 'driver' => 'monolog',
// 'handler' => MonologHandler::class,
// 'access_token' => env('ROLLBAR_TOKEN'),
// 'level' => env('ROLLBAR_LEVEL'),
// 'enabled' => true,
// 'environment' => env('ROLLBAR_ENVIRONMENT'),
// ]);
try{
$x = 4/0;
} catch(\Exception $exception) {
Rollbar::error('caught demo exception', ["details" => $exception->getMessage()]));
Rollbar::flush();
exit(1);
}
}
So when it is like this, the rollbar stays silent. But if I uncomment the initialisation, that works well, sending a debug message to the rollbar.
That doesn't work all over the project too.
Could you please advice me, what could I do here in order to make it work globally with initialising in every file?
upd: I've also cleared config cache and tried to make a rollbar as a default
Laravel in app/logging.php has a default channel configuration. Normally "default" should mean that there are some other working channel too but here, somehow it the meaning is like "the only used channel". Or I just do not fully understand how should it work. So my rollbar channel seems to be overriden by the another "default" one, that is why the system doesn't use it. So the solution is to switch the default channel:
'default' => env('LOG_CHANNEL', 'stack'),
when the rollbar is included to stack channel or just
'default' => env('LOG_CHANNEL', 'rollbar'),
when it is not.

Laravel Email Logging Channel

I have a Laravel 5.6 project and I want to configure it such that high level errors are emailed to me.
I have added an email channel to logging.php config file and specified Monolog's Swiftmailer as the handler but since it needs a mailer instance and message in its constructor I don't know what values should be supplied.
Any help is much appreciated.
PS: I do know there are packages for this purpose but think this should be simple enough to do manually.
'email' => [
'driver' => 'monolog',
'handler' => Monolog\Handler\SwiftMailerHandler::class,
'handler_with' => [
'mailer' => ?,
'message' => ?,
],
],
With Lavarel 7.x you can solve it like this
'smtp-sys' => [
'driver' => 'monolog',
'level' => 'info',
'handler' => SwiftMailerHandler::class,
'handler_with' => [
'mailer' => new Swift_Mailer( (new Swift_SmtpTransport(env('MAIL_HOST_SYS'), env('MAIL_PORT_SYS'), env('MAIL_ENCRYPTION', 'tls')))->setUsername(env('MAIL_USERNAME_SYS'))->setPassword(env('MAIL_PASSWORD_SYS'))),
'message' => (new Swift_Message('[LOG] Exception'))
->setFrom([env('MAIL_USERNAME_SYS') => 'Dev'])
->setTo([env('MAIL_USERNAME_SYS') => 'Dev'])
],
],
It might be a little late but from Symfony SwiftMailer documentation you should use something like this:
...
'email' => [
'driver' => 'monolog',
'level' => 'critical',
'handler' => SwiftMailerHandler::class,
'handler_with' => [
'mailer' => (new Swift_SmtpTransport(env('MAIL_HOST'), env('MAIL_PORT'), env('MAIL_ENCRYPTION')))
->setUsername(env('MAIL_USERNAME'))
->setPassword(env('MAIL_PASSWORD')),
'message' => (new Swift_Message('[LOG] Exception'))
->setFrom([env('LOG_MAIL_FROM_ADDRESS') => env('LOG_MAIL_FROM_NAME')])
->setTo([env('LOG_MAIL_TO_ADDRESS') => 'Dev'])
->setBody('Here is the message itself')
],
'formatter' => HtmlFormatter::class,
],
...

Zend 3 - using logger as service

I am quite novice with ZF3 and I can't figure out how should I define a logger module as a service and how could I use (reuse) it in other modules. The official documentation is poor from this point of view. Any short example would be good.
If you want to use zend-log in ZF app, after installation you need to do 2 thing:
To register Zend\Log in the application config under the 'modules' key.
Add config for your logger in global.php or module config
'log' => [
'MyLogger' => [
'writers' => [
'stream' => [
'name' => 'stream',
'priority' => \Zend\Log\Logger::ALERT,
'options' => [
'stream' => '/tmp/php_errors.log',
'formatter' => [
'name' => \Zend\Log\Formatter\Simple::class,
'options' => [
'format' => '%timestamp% %priorityName% (%priority%): %message% %extra%',
'dateTimeFormat' => 'c',
],
],
'filters' => [
'priority' => [
'name' => 'priority',
'options' => [
'operator' => '<=',
'priority' => \Zend\Log\Logger::INFO,
],
],
],
],
],
],
],
],
after that just take it from Service Manager and use it:
$logger = $container->get('MyLogger'); // <-- the key that you register in config above
$logger->info('Logging info message in the file');
You probably want to take logger from SM and than inject it in a class that you want to use it.
There is a god blog post about Logging with zend-log

Yii2 lajax translate manager scan error

When I try to run the ./yii translate/scan command, I got this error message after the Extreacting messages:
Exception 'yii\base\InvalidConfigException' with message 'Unable to locate message source for category 'DbMessageSource'.'
config/web.php
'components' => [
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\DbMessageSource',
'db' => 'db',
'sourceLanguage' => 'hu-HU', // Developer language
'sourceMessageTable' => '{{%language_source}}',
'messageTable' => '{{%language_translate}}',
'forceTranslation' => true,
'cachingDuration' => 86400,
'enableCaching' => true,
],
]
],
'translatemanager' => [
'class' => 'lajax\translatemanager\Component',
],
'modules' => [
'class' => 'lajax\translatemanager\Module',
'layout' => '//main',
'allowedIPs' => ['*'],
'roles' => ['Admin'],
]
]
config/console.php
'modules' => [
'translatemanager' => [
'class' => 'lajax\translatemanager\Module',
'tmpDir' => 'runtime', // Writable directory for the client-side temporary language files.
// IMPORTANT: must be identical for all applications (the AssetsManager serves the JavaScript files containing language elements from this directory).
//'root' => '#app', // The root directory of the project scan.
'phpTranslators' => ['::t'], // list of the php function for translating messages.
'jsTranslators' => ['lajax.t'], // list of the js function for translating messages.
'patterns' => ['*.js', '*.php'],// list of file extensions that contain language elements.
'ignoredCategories' => ['yii'], // these categories won’t be included in the language database.
'ignoredItems' => ['config'], // these files will not be processed.
'scanTimeLimit' => null, // increase to prevent "Maximum execution time" errors, if null the default max_execution_time will be used
'searchEmptyCommand' => '!', // the search string to enter in the 'Translation' search field to find not yet translated items, set to null to disable this feature
'defaultExportStatus' => 1, // the default selection of languages to export, set to 0 to select all languages by default
'defaultExportFormat' => 'json',// the default format for export, can be 'json' or 'xml'
'tables' => [ // Properties of individual tables
[
'connection' => 'db', // connection identifier
'table' => '{{%language}}', // table name
'columns' => ['name', 'name_ascii'], //names of multilingual fields
'category' => 'database-table-name',// the category is the database table name
],
]
],
],
'controllerMap' => [
'translate' => \lajax\translatemanager\commands\TranslatemanagerController::className(),
],
Do you have any idea what's wrong with my config or missing something?

EAuth Extension Yii2, Class nodge\eauth\EAuth does not exist

I am trying to use EAuth extension in Yii2 advanced application. I installed it through composer and it installed it under vendor directory and configured as mentioned here (did the config in common/config/main). So, following is the directory structure for that:
root
vendor
nodege
lightopenid
provider
*files go here*
yii2-eauth
src
*files go here*
EAuth.php is under src folder. In controller I have done this in use:
use nodge\eauth\EAuth;
and when I do this:
$eauth = Yii::$app->get('eauth')->getIdentity($serviceName);
I get the following error:
Class nodge\eauth\EAuth does not exist
What am I doing wrong? Any help?
Update:
This is my config:
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'eauth' => [
'class' => 'nodge\eauth\EAuth',
'popup' => true, // Use the popup window instead of redirecting.
'cache' => false, // Cache component name or false to disable cache. Defaults to 'cache' on production environments.
'cacheExpire' => 0, // Cache lifetime. Defaults to 0 - means unlimited.
'httpClient' => [
// uncomment this to use streams in safe_mode
//'useStreamsFallback' => true,
],
'services' => [// You can change the providers and their classes.
'google' => [
// register your app here: https://code.google.com/apis/console/
'class' => 'nodge\eauth\services\GoogleOAuth2Service',
'clientId' => '...',
'clientSecret' => '...',
'title' => 'Google',
],
'facebook' => [
// register your app here: https://developers.facebook.com/apps/
'class' => 'nodge\eauth\services\FacebookOAuth2Service',
'clientId' => '---',
'clientSecret' => '---',
],
'yahoo' => [
'class' => 'nodge\eauth\services\YahooOpenIDService',
//'realm' => '*.example.org', // your domain, can be with wildcard to authenticate on subdomains.
],
],
],
],

Categories