Laravel: como registar a informação para separar o ficheiro

Como especificar um ficheiro separado para logging INFO em Laravel 5.1?

Qualquer ajuda imediata será muito apreciável. Obrigado.
Author: Rohit Jindal, 2015-09-13

5 answers

Deseja registar especificamente info um ficheiro de registo e outro tipo de Registo noutro local? A minha solução pode não ajudar nesse caso, mas pode ser útil.

Para escrever um ficheiro de Registo noutro local, use o método useDailyFiles ou useFiles, e depois informe-se para aceder ao ficheiro de registo no local que acabou de indicar. Assim:

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

O primeiro parâmetro para ambos os métodos é o caminho do ficheiro de registo (que é criado se já não existir) e para useDailyFiles o segundo argumento é o número de dias que Laravel irá logar antes de apagar registros antigos. O valor padrão é ilimitado, então no meu exemplo eu não introduzi um valor.

 34
Author: TimothyBuktu, 2016-06-03 10:48:31

Se quiser adicionar outro manipulador monolog, poderá usar o método de configuração da aplicação.

Faça uma chamada para este método em bootstrap / app.ficheiro php imediatamente antes da variável $app ser devolvida:

$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;
 11
Author: Josip Ivic, 2015-09-13 17:41:00

Um simples assistente de registo que lhe permite aceder a vários ficheiros personalizados na altura. Você também pode adicionar o seu manipulador personalizado e definir o caminho do arquivo.

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();
        });
    }
}

Configuração\app.php (adicionar o prestador de Serviços)

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

Depois, em qualquer ponto da sua aplicação, pode ligar-se usando uma injecção de dependência (adicione a classe do seu construtor e ligue-a a log atributo class)

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

Você pode até personalizar a sua saída de logger chamando

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

E estará acessível quando você chamar o seu nome em qualquer lugar do seu aplicativo.

 6
Author: Romain Laneuville, 2017-07-16 02:51:03

Em Laravel 5.6 pode criar o seu próprio canal em {[[2]}. Se tiver actualizado a partir de uma versão Laravel mais antiga, terá de criar este ficheiro ( https://laravel.com/docs/5.6/upgrade).

Adicione isto à sua lista de canais em config\logging.php

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

Você pode então chamar qualquer um dos 8 níveis de registro assim:

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

Os registos serão armazenados em logs/your_file_name.log

 2
Author: Adam, 2018-07-15 16:45:48

O Laravel usa o monolog para o registo, mas usa uma versão mais antiga que não suporta múltiplos canais num único nível de Registo.

Aqui está uma sugestão que pode ajudar: laravel 5. 2 ficheiro de registo personalizado para diferentes tarefas

 0
Author: Jezzis, 2017-05-23 10:31:34