如何使用 Monolog 在日志文件中输出带有新行的字符串?

How to output a string with new lines in a log file using Monolog?

我正在尝试打印出来:

return $message . "\n\n in: "  . $file . "\n\n Line: " . $line ."\n\n\n Trace: \n\n". $trace;

\n 在传递时不起作用:

$this->logger->info($message, $variables);

我在日志输出的一行中得到了所有内容。我想显示跟踪、行、文件的错误,中间换行。

Monolog documentation 之后,在格式化程序部分 - 他们确实有一个名为 LineFormater 的 class,但我没有使用它:

LineFormatter: Formats a log record into a one-line string.

如果你好奇的话,这是我的完整代码:

<?php 
namespace MyApp\Modules;
use MyApp\Helpers\Session;
use MyApp\Core\Config;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// use Monolog\Handler\FirePHPHandler;
// use Monolog\Handler\MailHandler;

/**
 *
 *  Log Class: Handles logs
 *  This class uses Monolog repo:   https://github.com/Seldaek/monolog/
 *  Documentation for Monolog:      https://github.com/Seldaek/monolog/blob/master/doc/01-usage.md
 *
 */
class Log /*extends ExtendsName*/
{

/*=================================
=            Variables            =
=================================*/

    # Log Directory
    private $dir;

    # Logger Object 
    private $logger;

/*===============================
=            Methods            =
================================*/

    /**
     *
     *  Constructor
     *  1. Get the directory 
     *  2. Set the proper status group using the status code
     *  3. Set variables to logger obj
     *  4. Get log error group 
     *  5. Prepare message. 
     *  6. Output error log to file. 
     *
     */
    public function __construct($message, $code, $file, $line, $trace, $variables = array())
    {
        # Logger Obj
        $this->logger   = new Logger('MyApp');

        # Set Url 
        $this->dir      = $this->getLogDirectory();

        # Set logger variables 
        $this->logger->pushHandler(new StreamHandler($this->dir, Logger::DEBUG));

        # Set logger
        $loggerGroup    = $this->setLogger($code); 

        # Prepare Mesage
        $message        = $this->prepareLog($message, $file, $line, $trace);

        # Output log to the log file: 
        $this->logger->$loggerGroup($message, $variables);
    }



    /**
     *
     *  Get Log Directory
     *  @return     String      Directory with the customers name (or "general")
     *
     */
    private function getLogDirectory()
    {

        if (Session::exists(Config::$customer))
            # Get the customer name from the session
            $customerName = unserialize(Session::get('customer'))->name;

        if ( isset($customerName) ) {
            return '/var/log/appLog/'.$customerName.'.log';
        } else {
            return '/var/log/appLog/general.log';
        }
    }


    /**
     *
     *  Set Logger 
     *
     */
    private function setLogger($code)
    {
        # Get a status code 
        // $statusGroup = substr((string) $code, 0, 1);

        # Set the right log status
        // switch ($statusGroup) 
        switch ($code) 
        {
            # DEBUG (100):  Detailed debug information.
            case '100':
                return 'debug';
                break;

            # INFO (200):   Interesting events. Examples: User logs in, SQL logs.
            case '200':
                return 'info';
                break;

            # NOTICE (250): Normal but significant events.
            case '250':
                return 'notice';
                break;

            # WARNING (300): Exceptional occurrences that are not errors. Examples: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.
            case '300':
                return 'warning';
                break;

            # ERROR (400): Runtime errors that do not require immediate action but should typically be logged and monitored.
            case '400':
                return 'error';
                break;

            # CRITICAL (500): Critical conditions. Example: Application component unavailable, unexpected exception.
            case '500':
                return 'critical'; 
                break;

            # ALERT (550): Action must be taken immediately. Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.
            case '550':
                return 'alert'; 
                break;

            # EMERGENCY (600): Emergency: system is unusable.
            case '600':
                return 'emergency'; 
                break;

            default:
                return 'info';
                break;
        }
    }


    /**
     *
     *  Prepare Log Mesage
     *  @param      $message    String      The error message. 
     *  @param      $file       String      File path 
     *  @param      $line       ------      Line 
     *  @param      $line       String      Trace 
     *  @return                 String      Combine all the message output to 1 varaible. 
     *
     */
    private function prepareLog($message, $file, $line, $trace)
    {
        return $message . "\n\n in: "  . $file . "\n\n Line: " . $line ."\n\n\n Trace: \n\n". $trace;
    }

}

我认为您需要使用 LineFormatter。请查看下一个代码片段:

$logger = new Monolog\Logger('MyLoggerName');
$formatter = new Monolog\Formatter\LineFormatter(
    null, // Format of message in log, default [%datetime%] %channel%.%level_name%: %message% %context% %extra%\n
    null, // Datetime format
    true, // allowInlineLineBreaks option, default false
    true  // ignoreEmptyContextAndExtra option, default false
);
$debugHandler = new Monolog\Handler\StreamHandler('/tmp/my_debug.log', Monolog\Logger::DEBUG);
$debugHandler->setFormatter($formatter);
$logger->pushHandler($debugHandler);