Skip to content

Commit

Permalink
Merge remote-tracking branch 'official/master' into gelf-php-compat
Browse files Browse the repository at this point in the history
Conflicts:
	composer.json
  • Loading branch information
Benjamin Zikarsky committed Feb 22, 2014
2 parents f0ed3d8 + 08f09c2 commit b56ed7b
Show file tree
Hide file tree
Showing 28 changed files with 234 additions and 121 deletions.
5 changes: 4 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ php:
- 5.3
- 5.4
- 5.5
- hhvm

before_script:
- composer install --dev --prefer-source
- if [ "`phpenv version-name`" != "hhvm" ]; then echo "extension = mongo.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini; fi
- if [ "`phpenv version-name`" != "hhvm" ]; then echo "extension = amqp.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini; fi
- composer install --prefer-source

script: ./vendor/bin/phpunit
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"require-dev": {
"phpunit/phpunit": "~3.7.0",
"graylog2/gelf-php": "~1.0",
"raven/raven": "0.5.*",
"raven/raven": "~0.5",
"ruflin/elastica": "0.90.*",
"doctrine/couchdb": "dev-master",
"aws/aws-sdk-php": "~2.4.8"
Expand All @@ -34,7 +34,7 @@
"aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB"
},
"autoload": {
"psr-0": {"Monolog": "src/"}
"psr-4": {"Monolog\\": "src/Monolog"}
},
"extra": {
"branch-alias": {
Expand Down
2 changes: 1 addition & 1 deletion doc/extending.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ You can now use this handler in your logger:
```php
<?php

$logger->pushHandler(new PDOHandler(new PDO('sqlite:logs.sqlite'));
$logger->pushHandler(new PDOHandler(new PDO('sqlite:logs.sqlite')));

// You can now use your logger
$logger->addInfo('My logger is now ready');
Expand Down
2 changes: 1 addition & 1 deletion doc/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Monolog is available on Packagist ([monolog/monolog](http://packagist.org/packag
and as such installable via [Composer](http://getcomposer.org/).

```bash
php composer.phar require monolog/monolog '~1.4'
php composer.phar require monolog/monolog '~1.7'
```

If you do not use Composer, you can grab the code from GitHub, and use any
Expand Down
6 changes: 3 additions & 3 deletions src/Monolog/Formatter/HtmlFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ class HtmlFormatter extends NormalizerFormatter
Logger::NOTICE => '#3a87ad',
Logger::WARNING => '#c09853',
Logger::ERROR => '#f0ad4e',
Logger::CRITICAL => '#b94a48',
Logger::ALERT => '#d9534f',
Logger::EMERGENCY => '#ffffff',
Logger::CRITICAL => '#FF7708',
Logger::ALERT => '#C12A19',
Logger::EMERGENCY => '#000000',
);

/**
Expand Down
22 changes: 17 additions & 5 deletions src/Monolog/Formatter/LineFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,17 @@ class LineFormatter extends NormalizerFormatter
const SIMPLE_FORMAT = "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n";

protected $format;
protected $allowInlineLineBreaks;

/**
* @param string $format The format of the message
* @param string $dateFormat The format of the timestamp: one supported by DateTime::format
* @param string $format The format of the message
* @param string $dateFormat The format of the timestamp: one supported by DateTime::format
* @param bool $allowInlineLineBreaks Whether to allow inline line breaks in log entries
*/
public function __construct($format = null, $dateFormat = null)
public function __construct($format = null, $dateFormat = null, $allowInlineLineBreaks = false)
{
$this->format = $format ?: static::SIMPLE_FORMAT;
$this->allowInlineLineBreaks = $allowInlineLineBreaks;
parent::__construct($dateFormat);
}

Expand All @@ -47,13 +50,13 @@ public function format(array $record)
$output = $this->format;
foreach ($vars['extra'] as $var => $val) {
if (false !== strpos($output, '%extra.'.$var.'%')) {
$output = str_replace('%extra.'.$var.'%', $this->convertToString($val), $output);
$output = str_replace('%extra.'.$var.'%', $this->replaceNewlines($this->convertToString($val)), $output);
unset($vars['extra'][$var]);
}
}
foreach ($vars as $var => $val) {
if (false !== strpos($output, '%'.$var.'%')) {
$output = str_replace('%'.$var.'%', $this->convertToString($val), $output);
$output = str_replace('%'.$var.'%', $this->replaceNewlines($this->convertToString($val)), $output);
}
}

Expand Down Expand Up @@ -98,4 +101,13 @@ protected function convertToString($data)

return str_replace('\\/', '/', @json_encode($data));
}

protected function replaceNewlines($str)
{
if ($this->allowInlineLineBreaks) {
return $str;
}

return preg_replace('{[\r\n]+}', ' ', $str);
}
}
1 change: 0 additions & 1 deletion src/Monolog/Formatter/NormalizerFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ protected function normalizeException(Exception $e)
);

$trace = $e->getTrace();
array_shift($trace);
foreach ($trace as $frame) {
if (isset($frame['file'])) {
$data['trace'][] = $frame['file'].':'.$frame['line'];
Expand Down
2 changes: 0 additions & 2 deletions src/Monolog/Formatter/ScalarFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@

namespace Monolog\Formatter;

use Monolog\Formatter\NormalizerFormatter;

/**
* Formats data into an associative array of scalar values.
* Objects and arrays will be JSON encoded.
Expand Down
4 changes: 2 additions & 2 deletions src/Monolog/Handler/AbstractHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,8 @@ public function getLevel()
/**
* Sets the bubbling behavior.
*
* @param Boolean $bubble true means that this handler allows bubbling.
* false means that bubbling is not permitted.
* @param Boolean $bubble true means that this handler allows bubbling.
* false means that bubbling is not permitted.
* @return self
*/
public function setBubble($bubble)
Expand Down
4 changes: 2 additions & 2 deletions src/Monolog/Handler/CubeHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ class CubeHandler extends AbstractProcessingHandler
* Create a Cube handler
*
* @throws UnexpectedValueException when given url is not a valid url.
* A valid url must consists of three parts : protocol://host:port
* Only valid protocol used by Cube are http and udp
* A valid url must consists of three parts : protocol://host:port
* Only valid protocol used by Cube are http and udp
*/
public function __construct($url, $level = Logger::DEBUG, $bubble = true)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Monolog/Handler/DynamoDbHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ protected function write(array $record)
*/
protected function filterEmptyFields(array $record)
{
return array_filter($record, function($value) {
return array_filter($record, function ($value) {
return !empty($value) || false === $value || 0 === $value;
});
}
Expand Down
2 changes: 1 addition & 1 deletion src/Monolog/Handler/HandlerInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public function isHandling(array $record);
*
* @param array $record The record to handle
* @return Boolean true means that this handler handled the record, and that bubbling is not permitted.
* false means the record was either not processed or that this handler allows bubbling.
* false means the record was either not processed or that this handler allows bubbling.
*/
public function handle(array $record);

Expand Down
123 changes: 102 additions & 21 deletions src/Monolog/Handler/HipChatHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@
*/
class HipChatHandler extends SocketHandler
{
/**
* The maximum allowed length for the name used in the "from" field.
*/
const MAXIMUM_NAME_LENGTH = 15;

/**
* The maximum allowed length for the message.
*/
const MAXIMUM_MESSAGE_LENGTH = 9500;

/**
* @var string
*/
Expand All @@ -47,6 +57,11 @@ class HipChatHandler extends SocketHandler
*/
private $notify;

/**
* @var string
*/
private $format;

/**
* @param string $token HipChat API Token
* @param string $room The room that should be alerted of the message (Id or Name)
Expand All @@ -55,16 +70,22 @@ class HipChatHandler extends SocketHandler
* @param int $level The minimum logging level at which this handler will be triggered
* @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
* @param Boolean $useSSL Whether to connect via SSL.
* @param string $format The format of the messages (default to text, can be set to html if you have html in the messages)
*/
public function __construct($token, $room, $name = 'Monolog', $notify = false, $level = Logger::CRITICAL, $bubble = true, $useSSL = true)
public function __construct($token, $room, $name = 'Monolog', $notify = false, $level = Logger::CRITICAL, $bubble = true, $useSSL = true, $format = 'text')
{
if (!$this->validateStringLength($name, static::MAXIMUM_NAME_LENGTH)) {
throw new \InvalidArgumentException('The supplied name is too long. HipChat\'s v1 API supports names up to 15 UTF-8 characters.');
}

$connectionString = $useSSL ? 'ssl://api.hipchat.com:443' : 'api.hipchat.com:80';
parent::__construct($connectionString, $level, $bubble);

$this->token = $token;
$this->name = $name;
$this->notify = $notify;
$this->room = $room;
$this->format = $format;
}

/**
Expand Down Expand Up @@ -93,7 +114,7 @@ private function buildContent($record)
'room_id' => $this->room,
'notify' => $this->notify,
'message' => $record['formatted'],
'message_format' => 'text',
'message_format' => $this->format,
'color' => $this->getAlertColor($record['level']),
);

Expand Down Expand Up @@ -159,13 +180,19 @@ public function handleBatch(array $records)
return true;
}

$batchRecord = $this->combineRecords($records);
$batchRecords = $this->combineRecords($records);

if (!$this->isHandling($batchRecord)) {
return false;
$handled = false;
foreach ($batchRecords as $batchRecord) {
if ($this->isHandling($batchRecord)) {
$this->write($batchRecord);
$handled = true;
}
}

$this->write($batchRecord);
if (!$handled) {
return false;
}

return false === $this->bubble;
}
Expand All @@ -180,19 +207,17 @@ public function handleBatch(array $records)
*/
private function combineRecords($records)
{
$batchRecord = null;
$batchRecords = array();
$batchedMessages = array();
$messages = array();
$formattedMessages = array();
$level = 0;
$levelName = null;
$datetime = null;

foreach ($records as $record) {

$record = $this->processRecord($record);
$record['formatted'] = $this->getFormatter()->format($record);

$messages[] = $record['message'];
$formattedMessages[] = $record['formatted'];

if ($record['level'] > $level) {
$level = $record['level'];
Expand All @@ -202,18 +227,74 @@ private function combineRecords($records)
if (null === $datetime) {
$datetime = $record['datetime'];
}

$messages[] = $record['message'];
$messgeStr = implode(PHP_EOL, $messages);
$formattedMessages[] = $this->getFormatter()->format($record);
$formattedMessageStr = implode('', $formattedMessages);

$batchRecord = array(
'message' => $messgeStr,
'formatted' => $formattedMessageStr,
'context' => array(),
'extra' => array(),
);

if (!$this->validateStringLength($batchRecord['formatted'], static::MAXIMUM_MESSAGE_LENGTH)) {
// Pop the last message and implode the remainging messages
$lastMessage = array_pop($messages);
$lastFormattedMessage = array_pop($formattedMessages);
$batchRecord['message'] = implode(PHP_EOL, $messages);
$batchRecord['formatted'] = implode('', $formattedMessages);

$batchRecords[] = $batchRecord;
$messages = array($lastMessage);
$formattedMessages = array($lastFormattedMessage);

$batchRecord = null;
}
}

$batchRecord = array(
'message' => implode(PHP_EOL, $messages),
'formatted' => implode('', $formattedMessages),
'level' => $level,
'level_name' => $levelName,
'datetime' => $datetime,
'context' => array(),
'extra' => array(),
);
if (null !== $batchRecord) {
$batchRecords[] = $batchRecord;
}

// Set the max level and datetime for all records
foreach ($batchRecords as &$batchRecord) {
$batchRecord = array_merge(
$batchRecord,
array(
'level' => $level,
'level_name' => $levelName,
'datetime' => $datetime
)
);
}

return $batchRecords;
}

/**
* Validates the length of a string.
*
* If the `mb_strlen()` function is available, it will use that, as HipChat
* allows UTF-8 characters. Otherwise, it will fall back to `strlen()`.
*
* Note that this might cause false failures in the specific case of using
* a valid name with less than 16 characters, but 16 or more bytes, on a
* system where `mb_strlen()` is unavailable.
*
* @param string $str
* @param int $length
*
* @return bool
*/
private function validateStringLength($str, $length)
{
if (function_exists('mb_strlen')) {
return (mb_strlen($str) <= $length);
}

return $batchRecord;
return (strlen($str) <= $length);
}
}
26 changes: 13 additions & 13 deletions src/Monolog/Handler/PushoverHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,19 @@ class PushoverHandler extends SocketHandler
private $emergencyLevel;

/**
* @param string $token Pushover api token
* @param string|array $users Pushover user id or array of ids the message will be sent to
* @param string $title Title sent to the Pushover API
* @param integer $level The minimum logging level at which this handler will be triggered
* @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
* @param Boolean $useSSL Whether to connect via SSL. Required when pushing messages to users that are not
* the pushover.net app owner. OpenSSL is required for this option.
* @param integer $highPriorityLevel The minimum logging level at which this handler will start
* sending "high priority" requests to the Pushover API
* @param integer $emergencyLevel The minimum logging level at which this handler will start
* sending "emergency" requests to the Pushover API
* @param integer $retry The retry parameter specifies how often (in seconds) the Pushover servers will send the same notification to the user.
* @param integer $expire The expire parameter specifies how many seconds your notification will continue to be retried for (every retry seconds).
* @param string $token Pushover api token
* @param string|array $users Pushover user id or array of ids the message will be sent to
* @param string $title Title sent to the Pushover API
* @param integer $level The minimum logging level at which this handler will be triggered
* @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
* @param Boolean $useSSL Whether to connect via SSL. Required when pushing messages to users that are not
* the pushover.net app owner. OpenSSL is required for this option.
* @param integer $highPriorityLevel The minimum logging level at which this handler will start
* sending "high priority" requests to the Pushover API
* @param integer $emergencyLevel The minimum logging level at which this handler will start
* sending "emergency" requests to the Pushover API
* @param integer $retry The retry parameter specifies how often (in seconds) the Pushover servers will send the same notification to the user.
* @param integer $expire The expire parameter specifies how many seconds your notification will continue to be retried for (every retry seconds).
*/
public function __construct($token, $users, $title = null, $level = Logger::CRITICAL, $bubble = true, $useSSL = true, $highPriorityLevel = Logger::CRITICAL, $emergencyLevel = Logger::EMERGENCY, $retry = 30, $expire = 25200)
{
Expand Down
Loading

0 comments on commit b56ed7b

Please sign in to comment.