illuminated / console-logger
Logging and Notifications for Laravel Console Commands.
Installs: 67 312
Dependents: 0
Suggesters: 0
Security: 0
Stars: 87
Watchers: 6
Forks: 10
Open Issues: 0
Requires
- php: ^8.1
- illuminate/console: ^10.0
- illuminate/support: ^10.0
- illuminated/helper-functions: ^10.0
- monolog/monolog: ^3.0
- psr/http-message: ^1.0
- psr/log: ^1.0|^2.0|^3.0
- symfony/finder: ^6.2
Requires (Dev)
- guzzlehttp/guzzle: ^7.5
- illuminated/testing-tools: ^10.0
- mockery/mockery: ^1.5.1
- orchestra/testbench: ^8.0
- phpunit/phpunit: ^10.5
- dev-master
- 10.x-dev
- 10.0.0
- 9.x-dev
- 9.1.0
- 9.0.0
- 8.x-dev
- 8.3.0
- 8.2.0
- 8.1.0
- 8.0.0
- 7.x-dev
- 7.2.0
- 7.1.0
- 7.0.0
- 6.x-dev
- 6.3.0
- 6.2.0
- 6.1.0
- 6.0.0
- 5.8.x-dev
- 5.8.1
- 5.8.0
- 5.7.x-dev
- 5.7.5
- 5.7.4
- 5.7.3
- 5.7.2
- 5.7.1
- 5.7.0
- 5.6.x-dev
- 5.6.3
- 5.6.2
- 5.6.1
- 5.6.0
- 5.5.x-dev
- 5.5.4
- 5.5.3
- 5.5.2
- 5.5.1
- 5.5.0
- 5.4.x-dev
- 5.4.2
- 5.4.1
- 5.4.0
- 5.3.x-dev
- 5.3.2
- 5.3.1
- 5.3.0
- 5.2.x-dev
- 5.2.2
- 5.2.1
- 5.2.0
- 5.1.x-dev
- 5.1.2
- 5.1.1
- 5.1.0
- 2.1.5
- 2.1.4
- 2.1.3
- 2.1.2
- 2.1.1
- 2.1.0
- 2.0.7
- 2.0.6
- 2.0.5
- 2.0.4
- 2.0.3
- 2.0.2
- 2.0.1
- 2.0.0
- 1.1.9
- 1.1.8
- 1.1.7
- 1.1.6
- 1.1.5
- 1.1.4
- 1.1.3
- 1.1.2
- 1.1.1
- 1.0.12
- 1.0.11
- 1.0.10
- 1.0.9
- 1.0.8
- 1.0.7
- 1.0.6
- 1.0.5
- 1.0.4
- 1.0.3
- 1.0.2
- 1.0.1
- 1.0.0
- 0.1.38
- 0.1.37
- 0.1.36
- 0.1.35
- 0.1.34
- 0.1.33
- 0.1.32
- 0.1.31
- 0.1.30
- 0.1.29
- 0.1.28
- 0.1.27
- 0.1.26
- 0.1.25
- 0.1.24
- 0.1.23
- 0.1.22
- 0.1.21
- 0.1.20
- 0.1.19
- 0.1.18
- 0.1.17
- 0.1.16
- 0.1.15
- 0.1.14
- 0.1.13
- 0.1.12
- 0.1.11
- 0.1.10
- 0.1.9
- 0.1.8
- 0.1.7
- 0.1.6
- 0.1.5
- 0.1.4
- 0.1.3
- 0.1.2
- 0.1.1
This package is auto-updated.
Last update: 2024-11-06 21:57:06 UTC
README
Laravel Console Logger
Logging and Notifications for Laravel Console Commands.
Table of contents
- Usage
- Available methods
- Channels
- Error handling
- Guzzle 6+ integration
- Powered by Monolog
- Troubleshooting
- Sponsors
- License
Usage
-
Install the package via Composer:
composer require illuminated/console-logger
-
Use
Illuminated\Console\Loggable
trait:use Illuminated\Console\Loggable; class ExampleCommand extends Command { use Loggable; public function handle() { $this->logInfo('Hello World!'); } // ... }
-
Run the command and check your logs:
[2020-05-11 17:19:21]: [INFO]: Command `App\Console\Commands\ExampleCommand` initialized. [2020-05-11 17:19:21]: [INFO]: Host: `MyHost.local` (`10.0.1.1`). [2020-05-11 17:19:21]: [INFO]: Database host: `MyHost.local`, port: `3306`, ip: ``. [2020-05-11 17:19:21]: [INFO]: Database date: `2020-05-11 17:19:21`. [2020-05-11 17:19:21]: [INFO]: Hello World! [2020-05-11 17:19:21]: [INFO]: Execution time: 0.009 sec. [2020-05-11 17:19:21]: [INFO]: Memory peak usage: 8 MB.
Available methods
The Loggable
trait provides these PSR-3 methods:
logDebug()
logInfo()
logNotice()
logWarning()
logError()
logCritical()
logAlert()
logEmergency()
Use them in your console commands to log required information.
Channels
Log messages could be handled in multiple different ways.
It might be writing data into the log file, storing it in the database, sending an email, etc.
File channel
File channel simply writes log messages into the log file.
Each of the commands would have a separate folder within the storage/logs
dir.
For example, foo-bar
command logs would be stored in the storage/logs/foo-bar
folder.
You can customize the storage folder, and the max number of stored log files by overriding proper methods:
class ExampleCommand extends Command { use Loggable; protected function getLogPath() { return storage_path('logs/custom-folder/date.log'); } protected function getLogMaxFiles() { return 45; } // ... }
Notification channels
If you want to be notified about errors in your console commands - use notification channels.
Notification channels are optional and disabled by default. Each of them could be enabled and configured as needed.
By default, you'll get notifications with a level higher than NOTICE (see PSR-3 log levels). It means that you'll get NOTICE, WARNING, ERROR, CRITICAL, ALERT, and EMERGENCY notifications, by default.
Of course, you can customize that, as well as other channel-specific details.
Email channel
The email channel provides notifications via email.
Set the recipients, and email notifications are ready to go!
class ExampleCommand extends Command { use Loggable; protected function getEmailNotificationsRecipients() { return [ ['address' => 'john.doe@example.com', 'name' => 'John Doe'], ['address' => 'jane.smith@example.com', 'name' => 'Jane Smith'], ]; } // ... }
There's a bunch of methods related to the email channel.
By overriding those methods, you can change the subject, from
address, notification level, etc.
Deduplication is another useful feature worth mentioning. Sometimes the same error might occur many times in a row. For example, you're using an external web service that is down. Or imagine that the database server goes down. You'll get a lot of similar emails in those cases. Deduplication is the right solution for that.
You can enable it and adjust the time in seconds, for which deduplication works:
class ExampleCommand extends Command { use Loggable; protected function useEmailNotificationsDeduplication() { return true; } protected function getEmailNotificationsDeduplicationTime() { return 90; } // ... }
Database channel
The database channel provides a way to save notifications in the database.
The easiest way to start using it:
class ExampleCommand extends Command { use Loggable; protected function useDatabaseNotifications() { return true; } // ... }
Notifications would be stored in the iclogger_notifications
table, which would be automatically created if it doesn't exist yet.
Of course, you can customize the table name, and even the saving logic, by overriding proper methods:
class ExampleCommand extends Command { use Loggable; protected function useDatabaseNotifications() { return true; } protected function getDatabaseNotificationsTable() { return 'custom_notifications'; } protected function getDatabaseNotificationsCallback() { return function (array $record) { CustomNotification::create([ 'level' => $record['level'], 'level_name' => $record['level_name'], 'message' => $record['message'], 'context' => get_dump($record['context']), 'custom_field' => 'Foo Bar Baz!', ]); }; } // ... }
Error handling
Another cool feature that is enabled by default - is error handling.
The package automatically logs everything for you: severe problems - exceptions and fatal errors, and even small things, such as PHP notices and warnings.
Add notifications to that, and you'll immediately know when something goes wrong in your console commands!
Exceptions with context
Sometimes it's useful to pass an additional context of the thrown exception.
Use the Illuminated\Console\Exceptions\RuntimeException
for that:
use Illuminated\Console\Exceptions\RuntimeException; class ExampleCommand extends Command { use Loggable; public function handle() { throw new RuntimeException('Whoops! We have a problem!', [ 'some' => 123, 'extra' => true, 'context' => null, ]); } // ... }
[2020-05-11 17:19:21]: [ERROR]: Whoops! We have a problem!
array:5 [
"code" => 0
"message" => "Whoops! We have a problem!"
"file" => "/Applications/MAMP/htdocs/icl-test/app/Console/Commands/ExampleCommand.php"
"line" => 22
"context" => array:3 [
"some" => 123
"extra" => true
"context" => null
]
]
Guzzle 6+ integration
If you're using Guzzle, you might want to have a full log of your HTTP interactions.
The iclogger_guzzle_middleware()
function provides a pre-configured Guzzle Middleware for that:
use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; // Create a log middleware $logMiddleware = iclogger_guzzle_middleware($logger); // Add it to the HandlerStack $handler = HandlerStack::create(); $handler->push($logMiddleware); // Use the created handler in your Guzzle Client $client = new Client([ 'handler' => $handler, 'base_uri' => 'https://example.com', ]); // Now, all your HTTP requests and responses would be logged automatically! // $client->get('/foo');
If you're using JSON, you might want to get auto decoding for your request params and response bodies:
$logMiddleware = iclogger_guzzle_middleware($logger, 'json');
Also, you can disable logging of specific request params and/or response bodies, based on your custom logic:
use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; // Disable logging of request params for the `/foo` endpoint $shouldLogRequestParams = function (RequestInterface $request) { return ! str_ends_with($request->getUri(), '/foo'); }; // Disable logging of response bodies greater than 100 KB $shouldLogResponseBody = function (RequestInterface $request, ResponseInterface $response) { return $response->getHeaderLine('Content-Length') < 102400; }; $logMiddleware = iclogger_guzzle_middleware($logger, 'json', $shouldLogRequestParams, $shouldLogResponseBody);
Powered by Monolog
This package uses the powerful Monolog Logger.
You can access the underlying instance of Monolog by:
-
Using the command's
icLogger()
method:class ExampleCommand extends Command { use Loggable; public function handle() { $logger = $this->icLogger(); } // ... }
-
Or via the Laravel's Service Container:
$logger = app('log.iclogger');
Troubleshooting
Trait included, but nothing happens?
Loggable
trait overrides the initialize()
method:
trait Loggable { protected function initialize(InputInterface $input, OutputInterface $output) { $this->initializeLogging(); parent::initialize($input, $output); } // ... }
If your command overrides the initialize()
method too, you have to call the initializeLogging()
method by yourself:
class ExampleCommand extends Command { use Loggable; protected function initialize(InputInterface $input, OutputInterface $output) { // You have to call it first $this->initializeLogging(); // Then goes your custom code $this->foo = $this->argument('foo'); $this->bar = $this->argument('bar'); $this->baz = $this->argument('baz'); } // ... }
Several traits conflict?
If you're using another illuminated/console-%
package, you'll get the "traits conflict" error.
For example, if you're building a loggable command, which doesn't allow overlapping:
class ExampleCommand extends Command { use Loggable; use WithoutOverlapping; // ... }
You'll get the traits conflict, because both of those traits are overriding the initialize()
method:
If two traits insert a method with the same name, a fatal error is produced, if the conflict is not explicitly resolved.
To fix that - override the initialize()
method and resolve the conflict:
class ExampleCommand extends Command { use Loggable; use WithoutOverlapping; protected function initialize(InputInterface $input, OutputInterface $output) { // Initialize conflicting traits $this->initializeMutex(); $this->initializeLogging(); } // ... }
Sponsors
License
Laravel Console Logger is open-sourced software licensed under the MIT license.