代码之家  ›  专栏  ›  技术社区  ›  Imnotapotato

如何使用monolog在日志文件中输出包含新行的字符串?

  •  0
  • Imnotapotato  · 技术社区  · 7 年前

    我正在打印这个:

    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 但是我没有用它

    lineformatter:将日志记录格式化为单行字符串。

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

    <?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;
        }
    
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Bartosz Zasada    7 年前

    我认为你需要使用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);
    
    推荐文章