Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

monolog

I am trying to print out this:

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

the \n do not work when passing it though:

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

I get everything in one line in the log output. I want to display the errors with the trace, line, file, with a new line in between.

Following Monolog documentation, In the formater section - they do have a class named LineFormater, but I'm not using it anywere:

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

This is my full code if you're over-curious:

<?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;
    }

}
like image 729
Imnotapotato Avatar asked Mar 05 '23 21:03

Imnotapotato


1 Answers

I think you need to use LineFormatter. Please see the next code snippet:

$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);
like image 178
Viktar Pryshchepa Avatar answered Mar 07 '23 22:03

Viktar Pryshchepa