Как указать отдельный файл для logging INFO
в Laravel 5.1
?
Любая немедленная помощь будет очень заметной. Благодаря
Как указать отдельный файл для logging INFO
в Laravel 5.1
?
Любая немедленная помощь будет очень заметной. Благодаря
Вы хотите специально зарегистрировать info
в один файл журнала и другой тип журнала в другое место? Мое решение может не помочь в этом случае, но может быть полезно.
Чтобы записать файл журнала в другое место, используйте метод useDailyFiles
или useFiles
, а затем информацию для входа в файл журнала по указанному вами пути. Например:
Log::useDailyFiles(storage_path().'/logs/name-of-log.log');
Log::info([info to log]);
Первым параметром для обоих методов является путь к файлу журнала (который создается, если он еще не существует), а для useDailyFiles
второй аргумент - количество дней, которое Laravel будет регистрировать до стирания старых журналов. Значение по умолчанию не ограничено, поэтому в моем примере я не ввел значение.
В Laravel 5.6 вы можете создать свой собственный канал в config\logging.php
. Если вы обновили более старую версию Laravel, вам нужно создать этот файл (https://laravel.com/docs/5.6/upgrade).
Добавьте это к вашему массиву каналов в config\logging.php
'your_channel_name' => [
'driver' => 'single',
'path' => storage_path('logs/your_file_name.log'),
],
Затем вы можете назвать любой из 8 уровней ведения журнала следующим образом:
Illuminate\Support\Facades\Log::channel('your_channel_name')->info('your_message');
Журналы будут храниться в logs/your_file_name.log
Если вы хотите добавить еще один обработчик монолога, вы можете использовать метод configureMonologUsing приложения.
Поместите вызов этого метода в файл bootstrap/app.php прямо перед возвратом переменной $app:
$app->configureMonologUsing(function($monolog) {
$monolog->pushHandler(new StreamHandler('path/to/info.log', Logger::INFO, false)); // false value as third argument to disable bubbling up the stack
});
return $app;
Поскольку Laravel> = 5.6, мы можем использовать логи, чтобы он работал легко. Это позволяет создавать каналы журналов, которые можно обрабатывать как собственные файлы журналов с собственными драйверами, путями или уровнями. Вам просто нужно несколько строк, чтобы это заработало.
конфиг /logging.php:
return [
'channels' => [
'command' => [
'driver' => 'single',
'path' => storage_path('logs/command.log'),
'level' => 'debug',
],
],
];
Регистрируйте, где хотите, путем анализа названия канала:
Log::channel('command')->info('Something happened!');
Простой помощник журнала, который позволяет вам управлять несколькими пользовательскими файлами на лету. Вы также можете добавить свой собственный обработчик и задать путь к файлу.
App\Helper\LogToChannels.php
<?php
/**
* Logger helper to log into different files
*
* @package App\Helpers
* @author Romain Laneuville <[email protected]>
*/
namespace App\Helpers;
use Monolog\Logger;
use Monolog\Handler\HandlerInterface;
use Monolog\Handler\StreamHandler;
use Monolog\Formatter\LineFormatter;
/**
* Class LogToChannels
*
* @package App\Helpers
*/
class LogToChannels
{
/**
* The LogToChannels channels.
*
* @var Logger[]
*/
protected $channels = [];
/**
* LogToChannels constructor.
*/
public function __construct()
{
}
/**
* @param string $channel The channel to log the record in
* @param int $level The error level
* @param string $message The error message
* @param array $context Optional context arguments
*
* @return bool Whether the record has been processed
*/
public function log(string $channel, int $level, string $message, array $context = []): bool
{
// Add the logger if it doesn't exist
if (!isset($this->channels[$channel])) {
$handler = new StreamHandler(
storage_path() . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . $channel . '.log'
);
$handler->setFormatter(new LineFormatter(null, null, true, true));
$this->addChannel($channel, $handler);
}
// LogToChannels the record
return $this->channels[$channel]->{Logger::getLevelName($level)}($message, $context);
}
/**
* Add a channel to log in
*
* @param string $channelName The channel name
* @param HandlerInterface $handler The channel handler
* @param string|null $path The path of the channel file, DEFAULT storage_path()/logs
*
* @throws \Exception When the channel already exists
*/
public function addChannel(string $channelName, HandlerInterface $handler, string $path = null)
{
if (isset($this->channels[$channelName])) {
throw new \Exception('This channel already exists');
}
$this->channels[$channelName] = new Logger($channelName);
$this->channels[$channelName]->pushHandler(
new $handler(
$path === null ?
storage_path() . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . $channelName . '.log' :
$path . DIRECTORY_SEPARATOR . $channelName . '.log'
)
);
}
/**
* Adds a log record at the DEBUG level.
*
* @param string $channel The channel name
* @param string $message The log message
* @param array $context The log context
*
* @return bool Whether the record has been processed
*/
public function debug(string $channel, string $message, array $context = []): bool
{
return $this->log($channel, Logger::DEBUG, $message, $context);
}
/**
* Adds a log record at the INFO level.
*
* @param string $channel The channel name
* @param string $message The log message
* @param array $context The log context
*
* @return bool Whether the record has been processed
*/
public function info(string $channel, string $message, array $context = []): bool
{
return $this->log($channel, Logger::INFO, $message, $context);
}
/**
* Adds a log record at the NOTICE level.
*
* @param string $channel The channel name
* @param string $message The log message
* @param array $context The log context
*
* @return bool Whether the record has been processed
*/
public function notice(string $channel, string $message, array $context = []): bool
{
return $this->log($channel, Logger::NOTICE, $message, $context);
}
/**
* Adds a log record at the WARNING level.
*
* @param string $channel The channel name
* @param string $message The log message
* @param array $context The log context
*
* @return bool Whether the record has been processed
*/
public function warn(string $channel, string $message, array $context = []): bool
{
return $this->log($channel, Logger::WARNING, $message, $context);
}
/**
* Adds a log record at the WARNING level.
*
* @param string $channel The channel name
* @param string $message The log message
* @param array $context The log context
*
* @return bool Whether the record has been processed
*/
public function warning(string $channel, string $message, array $context = []): bool
{
return $this->log($channel, Logger::WARNING, $message, $context);
}
/**
* Adds a log record at the ERROR level.
*
* @param string $channel The channel name
* @param string $message The log message
* @param array $context The log context
*
* @return bool Whether the record has been processed
*/
public function err(string $channel, string $message, array $context = []): bool
{
return $this->log($channel, Logger::ERROR, $message, $context);
}
/**
* Adds a log record at the ERROR level.
*
* @param string $channel The channel name
* @param string $message The log message
* @param array $context The log context
*
* @return bool Whether the record has been processed
*/
public function error(string $channel, string $message, array $context = []): bool
{
return $this->log($channel, Logger::ERROR, $message, $context);
}
/**
* Adds a log record at the CRITICAL level.
*
* @param string $channel The channel name
* @param string $message The log message
* @param array $context The log context
*
* @return bool Whether the record has been processed
*/
public function crit(string $channel, string $message, array $context = []): bool
{
return $this->log($channel, Logger::CRITICAL, $message, $context);
}
/**
* Adds a log record at the CRITICAL level.
*
* @param string $channel The channel name
* @param string $message The log message
* @param array $context The log context
*
* @return Boolean Whether the record has been processed
*/
public function critical(string $channel, string $message, array $context = []): bool
{
return $this->log($channel, Logger::CRITICAL, $message, $context);
}
/**
* Adds a log record at the ALERT level.
*
* @param string $channel The channel name
* @param string $message The log message
* @param array $context The log context
*
* @return bool Whether the record has been processed
*/
public function alert(string $channel, string $message, array $context = []): bool
{
return $this->log($channel, Logger::ALERT, $message, $context);
}
/**
* Adds a log record at the EMERGENCY level.
*
* @param string $channel The channel name
* @param string $message The log message
* @param array $context The log context
*
* @return bool Whether the record has been processed
*/
public function emerg(string $channel, string $message, array $context = []): bool
{
return $this->log($channel, Logger::EMERGENCY, $message, $context);
}
/**
* Adds a log record at the EMERGENCY level.
*
* @param string $channel The channel name
* @param string $message The log message
* @param array $context The log context
*
* @return bool Whether the record has been processed
*/
public function emergency(string $channel, string $message, array $context = []): bool
{
return $this->log($channel, Logger::EMERGENCY, $message, $context);
}
}
App\Providers\LogToChannelsServiceProvider.php
<?php
/**
* Logger service provider to be abled to log in different files
*
* @package App\Providers
* @author Romain Laneuville <[email protected]>
*/
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Helpers\LogToChannels;
/**
* Class LogToChannelsServiceProvider
*
* @package App\Providers
*/
class LogToChannelsServiceProvider extends ServiceProvider
{
/**
* Initialize the logger
*
* @return void
*/
public function register()
{
$this->app->singleton('App\Helpers\LogToChannels', function () {
return new LogToChannels();
});
}
}
config\app.php(добавить поставщика услуг)
// Register Service Providers
$app->register(App\Providers\LogToChannelsServiceProvider::class);
Затем в любом месте вашего приложения вы можете вызывать использование инъекции зависимостей (добавьте класс в свой конструктор и привяжите его к атрибуту класса log
)
$this->log->info('logger_name', 'Log message');
$this->log->error('other_logger_name', 'Log message', $someContext);
Вы даже можете настроить вывод журнала, вызывая
$this->log->addChannel('channel_name', $customHandler);
И он будет доступен, когда вы будете называть его имя в любом месте вашего приложения.
Laravel использует монолог для ведения журнала, но использует более старую версию, которая не поддерживает несколько каналов на одном уровне журнала.
Вот предложение, которое может помочь: файл журнала laravel 5.2 для разных задач