Web and GRPC bundles include default integration with https://github.com/Seldaek/monolog to manage logs.
The extension does not require any default configuration. Use Spiral\Monolog\Bootloader\MonologBootloader
to
declare handler and log-formatter for specific channel:
namespace App\Bootloader;
use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Monolog\Bootloader\MonologBootloader;
class LoggingBootloader extends Bootloader
{
protected const DEPENDENCIES = [
MonologBootloader::class
];
public function boot(MonologBootloader $monolog)
{
$monolog->addHandler(
'my-channel',
$monolog->logRotate(directory('runtime') . 'logs/my-channel.log')
);
}
}
You can use any monolog handler as the second argument. Make sure to add your Bootloader at the top of the LOAD list.
You receive default
logger using Psr\Log\LoggerInterface
dependency:
public function index(LoggerInterface $logger)
{
$logger->alert('message');
}
To get logger for specific channel use Spiral\Logger\LogsInterface
:
use Spiral\Logger\LogsInterface;
// ...
public function index(LogsInterface $logs)
{
$logs->getLogger('my-channel')->alert('message');
}
Make sure to enable default handler to save content to the file:
namespace App\Bootloader;
use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Monolog\Bootloader\MonologBootloader;
class LoggingBootloader extends Bootloader
{
protected const DEPENDENCIES = [
MonologBootloader::class
];
/**
* @param MonologBootloader $monolog
*/
public function boot(MonologBootloader $monolog)
{
$monolog->addHandler(
'default',
$monolog->logRotate(directory('runtime') . 'logs/debug.log')
);
}
}
You can use Spiral\Logger\Traits\LoggerTrait
to assign Logger to any class quickly. The class name will be used as a channel name:
use Spiral\Logger\Traits\LoggerTrait;
class HomeController
{
use LoggerTrait;
public function index()
{
$this->getLogger()->alert('message');
}
}
And assign logger to it:
public function boot(MonologBootloader $monolog)
{
$monolog->addHandler(
HomeController::class,
$monolog->logRotate(directory('runtime') . 'logs/home-controller.log') // handler
);
}
LoggerTrait works only inside
$app->serve()
method via global IoC scope.
To aggregate all application errors into a single log file subscribe to default
channel:
namespace App\Bootloader;
use Monolog\Logger;
use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Monolog\Bootloader\MonologBootloader;
class LoggingBootloader extends Bootloader
{
protected const DEPENDENCIES = [
MonologBootloader::class
];
/**
* @param MonologBootloader $monolog
*/
public function boot(MonologBootloader $monolog)
{
$monolog->addHandler(
'default',
$monolog->logRotate(directory('runtime') . 'logs/errors.log', Logger::ERROR) // only ERROR and above
);
}
}
Use the second argument of dump
function to dump directly into default
log channel:
dump('hello', \Spiral\Debug\Dumper::LOGGER);