コード例 #1
5
 /**
  * {@inheritDoc}
  */
 public function register(Container $container)
 {
     // Append custom settings with missing params from default settings
     $container['settings']['logger'] = self::mergeWithDefaultSettings($container['settings']['logger']);
     /**
      * Add dependency (DI).
      *
      * @param Container $c
      *
      * @return Logger
      */
     $container['logger'] = function (Container $c) {
         $settings = $c['settings']['logger'];
         $loggerFormat = "[%datetime%] %level_name% %message% %context% %extra%\n";
         $loggerTimeFormat = "Y-m-d H:i:s";
         $loggerTimeZone = new DateTimeZone('Europe/Berlin');
         $logger = new Logger($settings['name']);
         if ($settings['color']) {
             $logger->pushProcessor(new ConsoleColorProcessor());
         }
         $logger->pushProcessor(new CleanupProcessor($settings['trimPaths']));
         $logger->pushProcessor(new IntrospectionProcessor(Logger::WARNING));
         $logger->pushProcessor(new ProcessIdProcessor());
         $logger->pushProcessor(new PsrLogMessageProcessor());
         $logger->setTimezone($loggerTimeZone);
         $logger->useMicrosecondTimestamps(false);
         // Using microseconds is buggy (2016-08-04)
         $formatter = new LineFormatter($loggerFormat, $loggerTimeFormat);
         $formatter->ignoreEmptyContextAndExtra(true);
         $defaultHandler = new StreamHandler('php://stdout', $settings['level'], $bubble = false);
         $defaultHandler->setFormatter($formatter);
         $logger->pushHandler($defaultHandler);
         $errorHandler = new StreamHandler('php://stderr', Logger::ERROR, $bubble = false);
         $errorHandler->setFormatter($formatter);
         $logger->pushHandler($errorHandler);
         // Register logger as default PHP error, exception and shutdown handler
         // Note: Make sure only this handler handles errors (set $callPrevious to false)
         $errorHandler = ErrorHandler::register($logger, $errorLevelMap = false, $exceptionLevelMap = false);
         $errorHandler->registerErrorHandler($levelMap = [], $callPrevious = false);
         $errorHandler->registerExceptionHandler($levelMap = [], $callPrevious = false);
         return $logger;
     };
 }
 public function addDebugLogger(Logger $logger, SymfonyStyle $output)
 {
     $lineFormatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message%\n");
     $lineFormatter->allowInlineLineBreaks(true);
     $lineFormatter->ignoreEmptyContextAndExtra(true);
     $stdoutHandler = new PsrHandler(new ConsoleLogger($output));
     $stdoutHandler->setFormatter($lineFormatter);
     $logger->pushHandler($stdoutHandler);
 }
コード例 #3
2
 /**
  * @param FormatterInterface $formatter
  *
  * @return array
  */
 public function getFormattedLogArray($formatter = null)
 {
     $res = [];
     if ($formatter === null) {
         $formatter = new LineFormatter();
     }
     foreach ($this->buffer as $record) {
         $res[] = trim($formatter->format($record));
     }
     return $res;
 }
コード例 #4
1
 /**
  * @covers ::getDefaultFormatter
  */
 public function testHandlerUsesLineFormatterWhichIgnoresEmptyArrays()
 {
     $record = array('message' => 'msg', 'context' => array(), 'level' => Logger::DEBUG, 'level_name' => Logger::getLevelName(Logger::DEBUG), 'channel' => 'channel', 'datetime' => new \DateTime(), 'extra' => array());
     $expectedFormatter = new LineFormatter(null, null, true, true);
     $expected = $expectedFormatter->format($record);
     $handlerFormatter = $this->handler->getFormatter();
     $actual = $handlerFormatter->format($record);
     $this->assertEquals($expected, $actual, 'Empty context and extra arrays should not be rendered');
 }
コード例 #5
1
ファイル: Sloop.php プロジェクト: jhnbrnn/Sloop
 protected function setLogger(&$c)
 {
     $c['Logger'] = function () {
         $log = new Logger('ErrorLogger');
         $handler = new ErrorLogHandler();
         $formatter = new LineFormatter();
         $formatter->includeStacktraces();
         $handler->setFormatter($formatter);
         $log->pushHandler($handler);
         return $log;
     };
 }
コード例 #6
1
 /**
  * {@inheritdoc}
  */
 public function format(array $record)
 {
     $record['start_tag'] = '';
     $record['end_tag'] = '';
     if ($record['level'] >= Logger::ERROR) {
         $record['start_tag'] = '<error>';
         $record['end_tag'] = '</error>';
     } elseif ($record['level'] == Logger::FAIL) {
         $record['start_tag'] = '<fail>';
         $record['end_tag'] = '</fail>';
     } elseif ($record['level'] >= Logger::WARNING) {
         $record['start_tag'] = '<info>';
         $record['end_tag'] = '</info>';
     } elseif ($record['level'] >= Logger::NOTICE) {
         $record['start_tag'] = '<comment>';
         $record['end_tag'] = '</comment>';
     } elseif ($record['level'] >= Logger::INFO) {
         $record['start_tag'] = '<info>';
         $record['end_tag'] = '</info>';
     } elseif ($record['level'] >= Logger::DEBUG) {
         $record['start_tag'] = '<comment>';
         $record['end_tag'] = '</comment>';
     }
     return parent::format($record);
 }
コード例 #7
1
    /**
     * {@inheritdoc}
     */
    public function format(array $record)
    {
        // Retrieve the line and file if set and remove them from the formatted extra
        $file = $line = '';
        if (isset($record['extra']['file'])) {
            $file = $record['extra']['file'];
            unset($record['extra']['file']);
        }
        if (isset($record['extra']['line'])) {
            $line = $record['extra']['line'];
            unset($record['extra']['line']);
        }

        // Format record according with LineFormatter
        $message = parent::format($record);

        // Create JSON object describing the appearance of the message in the console
        $json = json_encode(array(
            array(
                'Type'  => $this->logLevels[$record['level']],
                'File'  => $file,
                'Line'  => $line,
                'Label' => $record['channel'],
            ),
            $message,
        ));

        // The message itself is a serialization of the above JSON object + it's length
        return sprintf(
            '%s|%s|',
            strlen($json),
            $json
        );
    }
コード例 #8
1
 /**
  * {@inheritdoc}
  */
 public function format(array $record)
 {
     $str = parent::format($record);
     $str = str_replace('%time%', $record['datetime']->format('H:i:s'), $str);
     $str = str_replace('%csv%', $this->csvify($record['context']), $str);
     return rtrim($str, $this->delimiter);
 }
コード例 #9
1
 /**
  * {@inheritdoc}
  */
 protected function normalize($data)
 {
     if ($data instanceof Exception) {
         return $this->normalizeException($data);
     }
     return parent::normalize($data);
 }
コード例 #10
1
 protected function normalize($data)
 {
     if (is_object($data) && !$data instanceof \DateTime) {
         $data = ["[object] (" . get_class($data) . ")" => get_object_vars($data)];
     }
     return parent::normalize($data);
 }
コード例 #11
1
ファイル: SlackHandler.php プロジェクト: 4Queen/php-buildpack
 /**
  * Builds the body of API call
  *
  * @param  array  $record
  * @return string
  */
 private function buildContent($record)
 {
     $dataArray = array('token' => $this->token, 'channel' => $this->channel, 'username' => $this->username, 'text' => '', 'attachments' => array());
     if ($this->useAttachment) {
         $attachment = array('fallback' => $record['message'], 'color' => $this->getAttachmentColor($record['level']));
         if ($this->useShortAttachment) {
             $attachment['fields'] = array(array('title' => $record['level_name'], 'value' => $record['message'], 'short' => false));
         } else {
             $attachment['fields'] = array(array('title' => 'Message', 'value' => $record['message'], 'short' => false), array('title' => 'Level', 'value' => $record['level_name'], 'short' => true));
         }
         if ($this->includeExtra) {
             $extra = '';
             foreach ($record['extra'] as $var => $val) {
                 $extra .= $var . ': ' . $this->lineFormatter->stringify($val) . " | ";
             }
             $extra = rtrim($extra, " |");
             $attachment['fields'][] = array('title' => "Extra", 'value' => $extra, 'short' => false);
         }
         $dataArray['attachments'] = json_encode(array($attachment));
     } else {
         $dataArray['text'] = $record['message'];
     }
     if ($this->iconEmoji) {
         $dataArray['icon_emoji'] = ":{$this->iconEmoji}:";
     }
     return http_build_query($dataArray);
 }
コード例 #12
1
 /**
  * {@inheritdoc}
  */
 public function format(array $record)
 {
     // Get the Color Scheme
     $colorScheme = $this->getColorScheme();
     // Let the parent class to the formatting, yet wrap it in the color linked to the level
     return $colorScheme->getColorizeString($record['level']) . trim(parent::format($record)) . $colorScheme->getResetString() . "\n";
 }
コード例 #13
1
 /**
  * {@inheritdoc}
  */
 public function format(array $record)
 {
     $tag = strtolower($record['level_name']);
     $record['start_tag'] = '<' . $tag . '>';
     $record['end_tag'] = '</' . $tag . '>';
     return parent::format($record);
 }
コード例 #14
1
ファイル: LineFormatter.php プロジェクト: yapeal/yapeal-ng
 /**
  * @param mixed $data
  *
  * @return mixed
  * @throws \InvalidArgumentException
  * @throws \RuntimeException
  */
 protected function normalize($data)
 {
     if ($data instanceof \DateTime) {
         return substr($data->format($this->dateFormat), 0, 14);
     }
     return parent::normalize($data);
 }
コード例 #15
1
 /**
  * @param array $record
  * @return array|mixed|string
  */
 public function format(array $record)
 {
     $output = parent::format($record);
     if ($this->editFormatted) {
         $output = $this->editFormatted($output);
     }
     return $output;
 }
コード例 #16
1
 /**
  * {@inheritdoc}
  */
 public function format(array $record)
 {
     $output = parent::format($record);
     $output .= PHP_EOL . print_r($_SERVER, true);
     $output .= PHP_EOL . print_r($_SESSION, true);
     return $output;
     //return str_replace('\n', '<br>', $output);
 }
コード例 #17
1
 protected function normalize($data)
 {
     if ($data instanceof CsvFile) {
         return "csv file: " . $data->getFilename();
     } else {
         return parent::normalize($data);
     }
 }
コード例 #18
1
 /**
  * @param string $format The format of the message
  * @param Boolean $logContext If true add multiple rows containing Context information
  * @param Boolean $logExtra If true add multiple rows containing Extra information
  * @param integer $numberOfWords The number of words to show.
  */
 public function __construct($format = null, $logContext = true, $logExtra = true, $numberOfWords = 2)
 {
     $this->format = $format ?: static::SIMPLE_FORMAT;
     $this->numberOfWords = $numberOfWords;
     $this->logContext = $logContext;
     $this->logExtra = $logExtra;
     parent::__construct();
 }
コード例 #19
1
ファイル: DbFormatter.php プロジェクト: starweb/starlit-db
 /**
  * {@inheritdoc}
  */
 public function format(array $record)
 {
     $output = trim(parent::format($record));
     if ($this->maxLength !== null && strlen($output) > $this->maxLength) {
         $output = substr($output, 0, $this->maxLength - 3) . '...';
     }
     return $output;
 }
コード例 #20
1
 /**
  * @param array $record
  * @return mixed|string
  */
 public function format(array $record)
 {
     $this->logCounter++;
     $output = parent::format($record);
     $output = str_replace('%counter%', $this->logCounter, $output);
     $output = str_replace('%req-id%', $this->reqId, $output);
     return $output;
 }
コード例 #21
1
 /**
  * Formats a log record.
  *
  * @param  array $record A record to format
  * @return mixed The formatted record
  */
 public function format(array $record)
 {
     $formatted = parent::format($record);
     $levelName = strtolower($record['level_name']);
     $wrapped = sprintf('<%1$s>%2$s</%1$s>', $levelName, $formatted);
     $result = $this->getOutputFormatter()->format($wrapped);
     return $result;
 }
コード例 #22
1
 /**
  * Stringifies an array of key/value pairs to be used in attachment fields
  *
  * @param array $fields
  * @access protected
  * @return string
  */
 protected function stringify($fields)
 {
     $string = '';
     foreach ($fields as $var => $val) {
         $string .= $var . ': ' . $this->lineFormatter->stringify($val) . " | ";
     }
     $string = rtrim($string, " |");
     return $string;
 }
コード例 #23
1
 /**
  * {@inheritdoc}
  */
 public function format(array $record)
 {
     // Format record according with LineFormatter
     $message = parent::format($record);
     // Create JSON object describing the appearance of the message in the console
     $json = json_encode(array(array('Type' => $this->logLevels[$record['level']], 'File' => '', 'Line' => ''), $message));
     // The message itself is a serialization of the above JSON object + it's length
     return sprintf('%s|%s|', strlen($json), $json);
 }
コード例 #24
1
 public function format(array $record)
 {
     $record['codeInfo'] = '';
     if (isset($record['extra']['class']) && isset($record['extra']['function']) && isset($record['extra']['line'])) {
         $record['codeInfo'] = $record['extra']['class'] . '::' . $record['extra']['function'] . ':' . $record['extra']['line'];
     }
     //return parent
     return parent::format($record);
 }
コード例 #25
1
ファイル: LogFormatter.php プロジェクト: andrei2nikitin/quiz
 /**
  * @inheritdoc
  */
 public function stringify($value)
 {
     if (is_array($value)) {
         $result = [];
         foreach ($value as $k => $v) {
             $result[] = "{$k}={$v}";
         }
         return '[' . implode(', ', $result) . ']';
     }
     return parent::stringify($value);
 }
コード例 #26
1
 /**
  * Creates instance of Swift_Message to be sent
  *
  * @param  string         $content formatted email body to be sent
  * @param  array          $records Log records that formed the content
  * @return \Swift_Message
  */
 protected function buildMessage($content, array $records)
 {
     $message = null;
     if ($this->messageTemplate instanceof \Swift_Message) {
         $message = clone $this->messageTemplate;
         $message->generateId();
     } elseif (is_callable($this->messageTemplate)) {
         $message = call_user_func($this->messageTemplate, $content, $records);
     }
     if (!$message instanceof \Swift_Message) {
         throw new \InvalidArgumentException('Could not resolve message as instance of Swift_Message or a callable returning it');
     }
     if ($records) {
         $subjectFormatter = new LineFormatter($message->getSubject());
         $message->setSubject($subjectFormatter->format($this->getHighestRecord($records)));
     }
     $message->setBody($content);
     $message->setDate(time());
     return $message;
 }
コード例 #27
1
ファイル: LineFormatter.php プロジェクト: skvn/laraext
 public function __construct($format = null, $dateFormat = null, $allowInlineLineBreaks = false, $ignoreEmptyContextAndExtra = false)
 {
     parent::__construct($format, $dateFormat, $allowInlineLineBreaks, $ignoreEmptyContextAndExtra);
     if (empty($format)) {
         if (php_sapi_name() == "cli") {
             $this->format = "[%datetime%] (cli) %level_name%: %message% %extra%\n";
         } else {
             $this->format = "[%datetime%] (%extra.ip%:%user%) %extra.http_method% %extra.url%[%extra.referrer%]\n%message%\n%context%\n\n";
         }
     }
 }
コード例 #28
1
 /**
  * {@inheritdoc}
  */
 public function format(array $record)
 {
     $vars = $this->normalizerFormatter->format($record);
     $output = $this->format;
     foreach ($vars['extra'] as $var => $val) {
         if (false !== strpos($output, '%extra.' . $var . '%')) {
             $output = str_replace('%extra.' . $var . '%', var_export($val, true), $output);
             unset($vars['extra'][$var]);
         }
     }
     foreach ($vars as $var => $val) {
         if (false !== strpos($output, '%' . $var . '%')) {
             $val_output = '';
             if (is_array($val) && count($val) > 0 || is_array($val) === false) {
                 $val_output = var_export($val, true);
             }
             $output = str_replace('%' . $var . '%', $val_output, $output);
         }
     }
     return $output;
 }
コード例 #29
1
 /**
  * Get the plain text message with LineFormatter's format method and add
  * metadata including the trace id then return the json string.
  *
  * @param array $record A record to format
  * @return mixed The formatted record
  */
 public function format(array $record)
 {
     $message = parent::format($record);
     list($usec, $sec) = explode(" ", microtime());
     $usec = (int) ((double) $usec * 1000000000);
     $sec = (int) $sec;
     $payload = ['message' => $message, 'timestamp' => ['seconds' => $sec, 'nanos' => $usec], 'thread' => '', 'severity' => $record['level_name']];
     if (isset($_SERVER['HTTP_X_CLOUD_TRACE_CONTEXT'])) {
         $payload['traceId'] = explode("/", $_SERVER['HTTP_X_CLOUD_TRACE_CONTEXT'])[0];
     }
     return "\n" . json_encode($payload);
 }
コード例 #30
0
ファイル: TestCase.php プロジェクト: activecollab/jobsqueue
 /**
  * Set up test environment.
  */
 public function setUp()
 {
     parent::setUp();
     $this->link = new \MySQLi('localhost', 'root', '');
     if ($this->link->connect_error) {
         throw new \RuntimeException('Failed to connect to database. MySQL said: ' . $this->link->connect_error);
     }
     if (!$this->link->select_db('activecollab_jobs_queue_test')) {
         throw new \RuntimeException('Failed to select database.');
     }
     $this->connection = new MysqliConnection($this->link);
     $this->queue = new MySqlQueue($this->connection);
     $this->dispatcher = new Dispatcher($this->queue);
     $this->log_file_path = dirname(__DIR__) . '/logs/' . date('Y-m-d') . '.txt';
     if (is_file($this->log_file_path)) {
         unlink($this->log_file_path);
     }
     $this->log = new Logger('cli');
     $handler = new StreamHandler($this->log_file_path, Logger::DEBUG);
     $formatter = new LineFormatter();
     $formatter->includeStacktraces(true);
     $handler->setFormatter($formatter);
     $this->log->pushHandler($handler);
     $this->container = new Container(['dispatcher' => $this->dispatcher, 'log' => $this->log]);
 }