Using the Logger in Classes

Was this information useful?
Thank you for your feedback.

Want to use the default logger in classes using dependency injection? It's easy. Simply call the logger in your constructor:

namespace MyVendor\Something;

use Concrete\Core\Logging\Logger;

class MyClass
{

    protected $logger;

    public function __construct(Logger $logger) {
        $this->logger = $logger;    
    }

}

Then create the class via the application container.

$myClass = $this->app->make('MyVendor\Something\MyClass');

This will create an instance of MyClass, with the logger already configured for use with the application channel.

Most controllers should have access to $this->app. However, if you're outside the controller, you'll need to create an instance of the container object. You can always call:

$app = Facade::getFacadeApplication();

Or, simply call

$myClass = \Core::make('MyVendor\Something\MyClass');

Using the logger with a new Channel

Don't want to use the default Application channel when injecting the Logger via dependency injection? It's easy to switch channels.

class MyClass
{

    protected $logger;

    public function __construct(Logger $logger) {
        $logger = $logger->withName('shopping_cart');
        $this->logger = $logger;    
    }

}

Alternatively, simply subclass the core logger:

class ShoppingCartLogger extends Concrete\Core\Logging\Logger
{

    public function __construct()
    {
        parent::__construct('shopping_cart');
    }

}

class MyClass
{

    protected $logger;

    public function __construct(ShoppingCartLogger $logger) {
        $this->logger = $logger;    
    }

}