Laravel:如何将INFO记录到单独的文件中

Roh*_*dal 43 php laravel monolog laravel-5 laravel-5.1

如何为logging INFOin 指定单独的文件Laravel 5.1

任何直接的帮助都将非常值得注意.谢谢

Tim*_*ktu 42

您是否要专门登录info到一个日志文件而将另一个日志类型登录到另一个位置?在这种情况下,我的解决方案可能无济于事,但仍然有用.

要将日志文件写入另一个位置,请使用方法useDailyFilesuseFiles,然后使用info登录到您刚指定的路径中的日志文件.像这样:

    Log::useDailyFiles(storage_path().'/logs/name-of-log.log');
    Log::info([info to log]);
Run Code Online (Sandbox Code Playgroud)

两个方法的第一个参数是日志文件的路径(如果它尚不存在则创建),useDailyFiles第二个参数是Laravel在擦除旧日志之前将记录的天数.默认值是无限制的,所以在我的示例中我没有输入值.

  • 这仍然在Laravel 5.4中工作,我刚刚测试并使用它. (8认同)

Ada*_*dam 16

在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'),
        ],
Run Code Online (Sandbox Code Playgroud)

然后,您可以调用以下8个日志记录级别中的任何一个:

Illuminate\Support\Facades\Log::channel('your_channel_name')->info('your_message');
Run Code Online (Sandbox Code Playgroud)

日志将存储在 logs/your_file_name.log


Jos*_*vic 12

如果要添加另一个monolog处理程序,可以使用应用程序的configureMonologUsing方法.

在返回$ app变量之前,在bootstrap/app.php文件中调用此方法:

$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;
Run Code Online (Sandbox Code Playgroud)

  • @RohitJindal将`StreamHandler`换成`Monolog\Handler\StreamHandler`.您可能还会发现需要将`Logger`换成`Monolog\Logger`. (4认同)

Rom*_*lle 8

一个简单的记录器助手,允许您即时记录多个自定义文件.您还可以添加自定义处理程序并设置文件路径.

应用程序\辅助\ LogToChannels.php

<?php
/**
 * Logger helper to log into different files
 *
 * @package    App\Helpers
 * @author     Romain Laneuville <romain.laneuville@hotmail.fr>
 */

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

软件\供应商\ LogToChannelsServiceProvider.php

<?php
/**
 * Logger service provider to be abled to log in different files
 *
 * @package    App\Providers
 * @author     Romain Laneuville <romain.laneuville@hotmail.fr>
 */

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();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

config\app.php(添加服务提供者)

// Register Service Providers
$app->register(App\Providers\LogToChannelsServiceProvider::class);
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用依赖注入调用应用程序中的任何位置(在构造函数中添加类并将其绑定到log类属性)

$this->log->info('logger_name', 'Log message');
$this->log->error('other_logger_name', 'Log message', $someContext);
Run Code Online (Sandbox Code Playgroud)

您甚至可以通过调用自定义记录器输出

$this->log->addChannel('channel_name', $customHandler);
Run Code Online (Sandbox Code Playgroud)

当您在应用中的任何位置调用其名称时,它将可访问.


lin*_*lin 8

由于Laravel> = 5.6,我们可以使用对数通道使它以简单的方式工作。这使您可以创建日志通道,这些通道可以作为具有自己的驱动程序,路径或级别的自己的日志文件来处理。您只需要这几行就可以使其工作。

只需添加一个新频道(选择您的频道名称,例如“命令”)

config / logging.php:

return [
    'channels' => [ 
        'command' => [
            'driver' => 'single',
            'path' => storage_path('logs/command.log'),
            'level' => 'debug',
        ],
    ],
];
Run Code Online (Sandbox Code Playgroud)

通过解析通道名称记录所需的位置:

Log::channel('command')->info('Something happened!'); 
Run Code Online (Sandbox Code Playgroud)