Git Product home page Git Product logo

laravel-console-logg's Introduction

Laravel ConsoleLogg

PHPUnit suite codecov Latest Stable Version Total Downloads License FOSSA Status

Effortless PSR-3 Logger output to your console applications

Powered by Symfony's Console Logger

Table of contents

What does it do?

Logger channel for sharing messages between application and console commands

Typically, this requires a hacky solution, such as coupling your shared services with a console logger, or configuring multiple driver channels.

With ConsoleLogg you can have logs for your artisan commands, and behave as usual with http/controllers.

No code changes are required with logger usage

Supported:

  • Dependency Injection/autowiring LoggerInterface $logger & $logger->debug("yeet")
  • logger()->critical("Send help")
  • Log::alert("She find pictures in my email")
  • Log::info("Found <X> to be processed")
php artisan my:command -vvv
[debug] yeet
[critical] Send help
[alert] She find pictures in my email
[info] Found <X> to be processed

Install

  1. Install the package via Composer:

    composer require devthis/console-logg
  2. Enable logging channel console-logg

config/logging.php

    'channels' => [
        'stack' => [
            'driver' => 'stack',
-            'channels' => ['single'],
+            'channels' => ['console-logg', 'single'],
            'ignore_exceptions' => false,
        ],

Laravel - Logging Docs

Compatibility

Compatible Laravel
✔️ 10.*
✔️ 9.*
✔️ 8.*
✔️ 7.*
✔️ 6.*

Features

Artisan serve supported

Logger output will be shown in your local development server console.

Literally Effortless

Your application will not be coupled with ConsoleLogg.

There are no traits, classes, interfaces that you need to use. ConsoleLogg does not require any custom code, it just works.

The ConsoleLog Service Provider should be automatically added to your app, but if it hasn't, you can add it yourself to config/app.php

// generally only required when you have composer installed with --no-scripts

'providers' => [
    //...
    \DevThis\ConsoleLogg\Providers\ConsoleLoggServiceProvider::class,
];

Command-in-command

ConsoleLogg has (not yet) been tested for compatibility using artisan commands in a command with nested command calls

namespace App\Console\Commands;

use Illuminate\Console\Command;

class MyConsoleApp extends Command
{
    protected $description = '';
    protected $signature = 'my:app';

    public function handle(): int
    {
        //other:command may invoke services that use the Laravel Logger
        //these logs will still output to this current console
        $this->call('other:command');
        //...
        
        return 0;
    }
}

Light footprint

  • Zero external dependencies outside of Laravel contracts
  • No memory leakage (needs validation/tests)
    • One time use console logger is attached & detached alongside command execution
    • All references destroyed after command termination (letting PHP Garbage Collection do its thing)
  • Service Provider lazily works only when running in console mode

Usage

Verbosity

Verbosity is optionally controlled by either using -v arguments when running artisan.

This is not behaviour set by ConsoleLogg, it is defined in combination of Laravel & Symfony

ConsoleLogg may provide configuration for this in the future, if demand is apparent

Verbosity Level
default emergency, alert, critical, error, warning
-v notice + all of above
-vv info + all of above
-vvv debug + all of above

Examples

Running artisan

View example usage

Example #1 - SQL query logging

There are several guides/answers on the internet that enable you to send all SQL queries to your configured Logger.

With ConsoleLogg installed this means

Links (in no order):

Example #2 - Raw code

⚠️ REMINDER: n-o-t-h-i-n-g is special about this following code example

There are no traits, interfaces, or classes/dependencies that are involved to use ConsoleLogg once it's installed.

Souce code for example service

Source of App\Service\MyExampleService
namespace App\Service;

use Illuminate\Support\Facades\Log;
use Psr\Log\LoggerInterface;

class MyExampleService {
    private $logger;
    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }
    
    public function doSomethingCool(): void
    {
        // using Laravel's logger with DI/autowiring
        $this->logger->debug("A message that should have value when output to your application in general");
        
        // Facade
        Log::info("or just the facade if you love magic");
        
        // Helper function
        logger()->notice("or this weird helper function I guess");
        
        // ... <imaginary useful code here>
    }
}

Source code for Console Application

Source of App\Console\Commands\ExampleConsole
namespace App\Console\Commands;

use App\Service\ExampleService;
use Illuminate\Console\Command;

class ExampleConsole extends Command
{
    /**
     * The console command description.
     */
    protected $description = '';

    /**
     * The name and signature of the console command.
     */
    protected $signature = 'something';

    public function handle(ExampleService $exampleService): int
    {
        $exampleService->doSomethingCool();

        return 0;
    }
}

Running artisan

Artisan command output
not-root@linux:~/MyProject$ php artisan something -vv
[debug] A message that should have value when output to your application in general
[info] or just the facade if you love magic
[notice] or this weird helper function I guess

License

Laravel ConsoleLogg is open-sourced software licensed under the MIT license.

laravel-console-logg's People

Contributors

lfglopes avatar lvmade01 avatar verystrongfingers avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

lfglopes

laravel-console-logg's Issues

Laravel 10

Hi,

this cool package isn't working with Laravel 10 anymore. Laravel 10 uses Monolog 3 and now there is a declaration wrong:

   Symfony\Component\ErrorHandler\Error\FatalError 

  Declaration of DevThis\ConsoleLogg\LogHandlers\ConsoleApp::isHandling(array $record): bool must be compatible with Monolog\Handler\HandlerInterface::isHandling(Monolog\LogRecord $record): bool

  at vendor/devthis/console-logg/src/LogHandlers/ConsoleApp.php:22
     18▕     {
     19▕         return [];
     20▕     }
     21▕ 
  ➜  22▕     public function isHandling(array $record): bool
     23▕     {
     24▕         return true;
     25▕     }
     26▕ 

Fallback to emergency logger on HTTP requests

If I write Log::info('test') on an HTTP controller, the console-logg driver is not recognized and I get the following on laravel.log:

[2022-07-04 15:44:53] laravel.EMERGENCY: Unable to create configured logger. Using emergency logger. {"exception":"[object] (InvalidArgumentException(code: 0): Log [console-logg] is not defined. at /var/www/html/vendor/laravel/framework/src/Illuminate/Log/LogManager.php:192)
[stacktrace]
#0 /var/www/html/vendor/laravel/framework/src/Illuminate/Log/LogManager.php(118): Illuminate\\Log\\LogManager->resolve('console-logg')
#1 /var/www/html/vendor/laravel/framework/src/Illuminate/Log/LogManager.php(98): Illuminate\\Log\\LogManager->get('console-logg')
#2 /var/www/html/vendor/laravel/framework/src/Illuminate/Log/LogManager.php(87): Illuminate\\Log\\LogManager->driver('console-logg')
#3 /var/www/html/vendor/laravel/framework/src/Illuminate/Log/LogManager.php(241): Illuminate\\Log\\LogManager->channel('console-logg')
#4 [internal function]: Illuminate\\Log\\LogManager->Illuminate\\Log\\{closure}('console-logg', 1)
#5 /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Collection.php(638): array_map(Object(Closure), Array, Array)
#6 /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Traits/EnumeratesValues.php(311): Illuminate\\Support\\Collection->map(Object(Closure))
#7 /var/www/html/vendor/laravel/framework/src/Illuminate/Log/LogManager.php(242): Illuminate\\Support\\Collection->flatMap(Object(Closure))
#8 /var/www/html/vendor/laravel/framework/src/Illuminate/Log/LogManager.php(202): Illuminate\\Log\\LogManager->createStackDriver(Array)
#9 /var/www/html/vendor/laravel/framework/src/Illuminate/Log/LogManager.php(118): Illuminate\\Log\\LogManager->resolve('stack')
#10 /var/www/html/vendor/laravel/framework/src/Illuminate/Log/LogManager.php(98): Illuminate\\Log\\LogManager->get('stack')
#11 /var/www/html/vendor/laravel/framework/src/Illuminate/Log/LogManager.php(621): Illuminate\\Log\\LogManager->driver()
"} 

(...)

Send logs to console output AND default log channel?

Hi! Thank you for this package, this is exactly what I was looking for.

Question though: do I get it correctly that, once this package is installed, the logs from console command won't be sent to their default logging channel anymore? If that's the case, it's a downside for me: I want to be able to look up the output in my daily logs for scheduled commands.

Or maybe something is wrong in my setup? Thanks for clarifying!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.