I am trying to create custom Log classes in my application which use the default channel but write in a different file, but i can't find any relevant documentation for my needs.
Use case :
In UserService i want to call UserLogger::info('info');
which will write in user_log.php
In CarService i want to call CarLogger::info('info');
which will write in car_log.php
Currently i have an abstract class which has function :
protected static function setUpLogger(): \Psr\Log\LoggerInterface
{
return Log::build([
'driver' => 'single',
'path' => storage_path(static::$path),
]);
}
I am using it each time i'm calling custom loggers, but it's probably a very bad approach.
Does anyone have an idea on how i can achieve custom log classes in described way?
You need to add own channels, by editing config/logging.php
:
'user' => [
'driver' => 'single',
'path' => storage_path('logs/user_log.php'),
'level' => 'debug',
],
Then you can create logger using your new channel:
class UserLogger
{
public static function info($message, $context = []): void
{
Log::channel('user')->info($message, $context);
}
...
}
and now you can use CarLogger::info('info');
.
The same steps fro CarLogger
or any other separate loggers and you should be good to go.