php Laravel:如何记录信息以分隔文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32552450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:03:43  来源:igfitidea点击:

Laravel : How to Log INFO to separate file

phplaravellaravel-5laravel-5.1monolog

提问by Rohit Jindal

How to specify a separate file for logging INFOin Laravel 5.1?

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

Any immediate help will be highly appreciable. Thanks

任何立即的帮助都将是非常可观的。谢谢

采纳答案by TimothyBuktu

Do you want to specifically log infoto one log file and another log type to another location? My solution might not help in that case, but could still be useful.

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

To write a log file to another location, use the method useDailyFilesor useFiles, and then info to log to the log file at the path you just specified. Like so:

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

    Log::useDailyFiles(storage_path().'/logs/name-of-log.log');
    Log::info([info to log]);

The first parameter for both methods is the path of the log file (which is created if it doesn't already exist) and for useDailyFilesthe second argument is the number of days Laravel will log for before erasing old logs. The default value is unlimited, so in my example I haven't entered a value.

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

回答by Adam

In Laravel 5.6 you can create your own channel in config\logging.php. If you have upgraded from an older Laravel version you need to create this file (https://laravel.com/docs/5.6/upgrade).

在 Laravel 5.6 中,您可以在config\logging.php. 如果您从旧的 Laravel 版本升级,则需要创建此文件 ( https://laravel.com/docs/5.6/upgrade)。

Add this to you channel array in config\logging.php

将此添加到您的通道数组中 config\logging.php

'your_channel_name' => [
            'driver' => 'single',
            'path' => storage_path('logs/your_file_name.log'),
        ],

You can then call any of the 8 logging levelslike that:

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

Illuminate\Support\Facades\Log::channel('your_channel_name')->info('your_message');

The logs will be stored in logs/your_file_name.log

日志将存储在 logs/your_file_name.log

回答by Josip Ivic

If you would like add another monolog handler, you may use the application's configureMonologUsing method.

如果您想添加另一个 Monolog 处理程序,您可以使用应用程序的 configureMonologUsing 方法。

Place a call to this method in bootstrap/app.php file right before the $app variable is returned:

在 $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;

回答by Romain Laneuville

A simple logger helper that allows you to log to multiple custom files on the fly. You can also add your custom handler and set the file path.

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

App\Helper\LogToChannels.php

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

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 (add the service provider)

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

// Register Service Providers
$app->register(App\Providers\LogToChannelsServiceProvider::class);

Then anywhere in your app you can call using dependency injection (add the class in your constructor and bind it to a logclass attribute)

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

$this->log->info('logger_name', 'Log message');
$this->log->error('other_logger_name', 'Log message', $someContext);

You can even customize your logger output by calling

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

$this->log->addChannel('channel_name', $customHandler);

And it will be accessible when you will call its name anywhere in your app.

当您在应用程序的任何位置调用它的名称时,它就可以访问。

回答by lin

Since Laravel >= 5.6we can use Log Channelsto make it work in a easy way. This allows you to create log channels which can be handled as own log files with own drivers, paths or levels. You just need this few lines to make it work.

Laravel >= 5.6 开始,我们可以使用Log Channels让它以一种简单的方式工作。这允许您创建日志通道,这些通道可以作为具有自己的驱动程序、路径或级别的自己的日志文件进行处理。你只需要这几行就可以让它工作。

Simple add a new channel (choose your channel name, e.g. "command")

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

config/logging.php:

配置/logging.php:

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


Log where ever you want by parse the channel name:

通过解析频道名称记录您想要的任何位置:

Log::channel('command')->info('Something happened!'); 

回答by yesnik

To activate logging to file in Laravel 5.8 or 6:

要在 Laravel 5.8 或 6 中激活日志记录到文件:

  1. Edit .envfile:

    LOG_CHANNEL=single
    
  2. Use this in your code:

    use Illuminate\Support\Facades\Log;
    
    Log::debug('Hello');
    
  1. 编辑.env文件:

    LOG_CHANNEL=single
    
  2. 在您的代码中使用它:

    use Illuminate\Support\Facades\Log;
    
    Log::debug('Hello');
    

Message will be logged to storage/logs/laravel.log. This is a default pathfor singlechannel at config/logging.php.

消息将被记录到storage/logs/laravel.log. 这是默认pathsingle在信道config/logging.php