Reputation: 797
I'd like to have separate log files to store debug data for some of my API methods. Something like car_create.log
, car_update.log
, etc.
Can I achieve this with the built-in logging functionality? Isn't it some kind of wrong approach? Because it seems like almost nobody have same issues. Any advice or suggestions will be much appreciated!
Upvotes: 2
Views: 2225
Reputation: 2371
The Errors & Logging documentation informs that Monolog is the underlying logging package used by Laravel. You can use Monolog to do anything you want.
<?php
namespace App\Helpers\Common;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Carbon\Carbon;
class FileLogger extends Logger
{
protected $path = null;
public function __construct($name, $level = 'DEBUG', $path = null, array $processors = [ ])
{
$tz = static::$timezone = new \DateTimeZone(config('app.timezone'));
$handlers = [ ];
parent::__construct($name, $handlers, $processors);
$dtObj = Carbon::now($tz);
if ( ! $path) {
$path = $name . '-' . $dtObj->format('Y-m-d') . '.log';
}
$path = $this->path = storage_path('logs/' . $path);
$this->addStream($path, $level);
return $this;
}
public static function getLevelNum($level)
{
return static::getLevels()[ strtoupper($level) ];
}
public function addStream($path, $level = 'DEBUG')
{
if ( ! is_int($level)) {
$level = static::getLevelNum($level);
}
$this->pushHandler(new StreamHandler($path, $level));
return $this;
}
public function addRecord($level, $message, array $context = array())
{
if ( ! is_int($level)) {
$level = static::getLevelNum($level);
}
parent::addRecord($level, $message, $context);
return $this;
}
}
use App\Helpers\Common\FileLogger;
// ...
$level = 'DEBUG';
$logger = new FileLogger('NAME', $level);
$logger->addRecord($level, $message, $context);
Upvotes: 4