ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
Monolog\Handler\HipChatHandler Class Reference

Sends notifications through the hipchat api to a hipchat room. More...

+ Inheritance diagram for Monolog\Handler\HipChatHandler:
+ Collaboration diagram for Monolog\Handler\HipChatHandler:

Public Member Functions

 __construct ($token, $room, $name='Monolog', $notify=false, $level=Logger::CRITICAL, $bubble=true, $useSSL=true, $format='text', $host='api.hipchat.com', $version=self::API_V1)
 
 handleBatch (array $records)
 {Handles a set of records at once.
Parameters
array$recordsThe records to handle (an array of record arrays)
} More...
 
- Public Member Functions inherited from Monolog\Handler\SocketHandler
 __construct ($connectionString, $level=Logger::DEBUG, $bubble=true)
 
 close ()
 We will not close a PersistentSocket instance so it can be reused in other requests. More...
 
 closeSocket ()
 Close socket, if open. More...
 
 setPersistent ($persistent)
 Set socket connection to nbe persistent. More...
 
 setConnectionTimeout ($seconds)
 Set connection timeout. More...
 
 setTimeout ($seconds)
 Set write timeout. More...
 
 setWritingTimeout ($seconds)
 Set writing timeout. More...
 
 setChunkSize ($bytes)
 Set chunk size. More...
 
 getConnectionString ()
 Get current connection string. More...
 
 isPersistent ()
 Get persistent setting. More...
 
 getConnectionTimeout ()
 Get current connection timeout setting. More...
 
 getTimeout ()
 Get current in-transfer timeout. More...
 
 getWritingTimeout ()
 Get current local writing timeout. More...
 
 getChunkSize ()
 Get current chunk size. More...
 
 isConnected ()
 Check to see if the socket is currently available. More...
 
- Public Member Functions inherited from Monolog\Handler\AbstractProcessingHandler
 handle (array $record)
 {Handles a record.All records may be passed to this method, and the handler should discard those that it does not want to handle.The return value of this function controls the bubbling process of the handler stack. Unless the bubbling is interrupted (by returning true), the Logger class will keep on calling further handlers in the stack with a given log record.
Parameters
array$recordThe record to handle
Returns
bool 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.
} More...
 
- Public Member Functions inherited from Monolog\Handler\AbstractHandler
 __construct ($level=Logger::DEBUG, $bubble=true)
 
 isHandling (array $record)
 {Checks whether the given record will be handled by this handler.This is mostly done for performance reasons, to avoid calling processors for nothing.Handlers should still check the record levels within handle(), returning false in isHandling() is no guarantee that handle() will not be called, and isHandling() might not be called for a given record.
Parameters
array$recordPartial log record containing only a level key
Returns
bool
} More...
 
 handleBatch (array $records)
 {Handles a set of records at once.
Parameters
array$recordsThe records to handle (an array of record arrays)
} More...
 
 close ()
 Closes the handler. More...
 
 pushProcessor ($callback)
 {Adds a processor in the stack.
Parameters
callable$callback
Returns
self
} More...
 
 popProcessor ()
 {Removes the processor on top of the stack and returns it.
Returns
callable
} More...
 
 setFormatter (FormatterInterface $formatter)
 {Sets the formatter.
Parameters
FormatterInterface$formatter
Returns
self
} More...
 
 getFormatter ()
 {Gets the formatter.
Returns
FormatterInterface
} More...
 
 setLevel ($level)
 Sets minimum logging level at which this handler will be triggered. More...
 
 getLevel ()
 Gets minimum logging level at which this handler will be triggered. More...
 
 setBubble ($bubble)
 Sets the bubbling behavior. More...
 
 getBubble ()
 Gets the bubbling behavior. More...
 
 __destruct ()
 
 reset ()
 

Data Fields

const API_V1 = 'v1'
 Use API version 1. More...
 
const API_V2 = 'v2'
 Use API version v2. More...
 
const MAXIMUM_NAME_LENGTH = 15
 The maximum allowed length for the name used in the "from" field. More...
 
const MAXIMUM_MESSAGE_LENGTH = 9500
 The maximum allowed length for the message. More...
 

Protected Member Functions

 generateDataStream ($record)
 {} More...
 
 getAlertColor ($level)
 Assigns a color to each level of log records. More...
 
 write (array $record)
 {} More...
 
 finalizeWrite ()
 Finalizes the request by reading some bytes and then closing the socket. More...
 
- Protected Member Functions inherited from Monolog\Handler\SocketHandler
 write (array $record)
 Connect (if necessary) and write to the socket. More...
 
 pfsockopen ()
 Wrapper to allow mocking. More...
 
 fsockopen ()
 Wrapper to allow mocking. More...
 
 streamSetTimeout ()
 Wrapper to allow mocking. More...
 
 streamSetChunkSize ()
 Wrapper to allow mocking. More...
 
 fwrite ($data)
 Wrapper to allow mocking. More...
 
 streamGetMetadata ()
 Wrapper to allow mocking. More...
 
 generateDataStream ($record)
 
 getResource ()
 
- Protected Member Functions inherited from Monolog\Handler\AbstractProcessingHandler
 write (array $record)
 Writes the record down to the log of the implementing handler. More...
 
 processRecord (array $record)
 Processes a record. More...
 
- Protected Member Functions inherited from Monolog\Handler\AbstractHandler
 getDefaultFormatter ()
 Gets the default formatter. More...
 

Private Member Functions

 buildContent ($record)
 Builds the body of API call. More...
 
 buildHeader ($content)
 Builds the header of the API Call. More...
 
 combineRecords ($records)
 Combines multiple records into one. More...
 
 validateStringLength ($str, $length)
 Validates the length of a string. More...
 

Private Attributes

 $token
 
 $room
 
 $name
 
 $notify
 
 $format
 
 $host
 
 $version
 

Additional Inherited Members

- Protected Attributes inherited from Monolog\Handler\AbstractHandler
 $level = Logger::DEBUG
 
 $bubble = true
 
 $formatter
 
 $processors = array()
 

Detailed Description

Sends notifications through the hipchat api to a hipchat room.

Notes: API token - HipChat API token Room - HipChat Room Id or name, where messages are sent Name - Name used to send the message (from) notify - Should the message trigger a notification in the clients version - The API version to use (HipChatHandler::API_V1 | HipChatHandler::API_V2)

Author
Rafael Dohms rafae.nosp@m.l@do.nosp@m.h.ms
See also
https://www.hipchat.com/docs/api

Definition at line 29 of file HipChatHandler.php.

Constructor & Destructor Documentation

◆ __construct()

Monolog\Handler\HipChatHandler::__construct (   $token,
  $room,
  $name = 'Monolog',
  $notify = false,
  $level = Logger::CRITICAL,
  $bubble = true,
  $useSSL = true,
  $format = 'text',
  $host = 'api.hipchat.com',
  $version = self::API_V1 
)
Parameters
string$tokenHipChat API Token
string$roomThe room that should be alerted of the message (Id or Name)
string$nameName used in the "from" field.
bool$notifyTrigger a notification in clients or not
int$levelThe minimum logging level at which this handler will be triggered
bool$bubbleWhether the messages that are handled can bubble up the stack or not
bool$useSSLWhether to connect via SSL.
string$formatThe format of the messages (default to text, can be set to html if you have html in the messages)
string$hostThe HipChat server hostname.
string$versionThe HipChat API version (default HipChatHandler::API_V1)

Definition at line 98 of file HipChatHandler.php.

References Monolog\Handler\AbstractHandler\$bubble, Monolog\Handler\SocketHandler\$connectionString, Monolog\Handler\HipChatHandler\$format, Monolog\Handler\HipChatHandler\$host, Monolog\Handler\AbstractHandler\$level, Monolog\Handler\HipChatHandler\$name, Monolog\Handler\HipChatHandler\$notify, Monolog\Handler\HipChatHandler\$room, Monolog\Handler\HipChatHandler\$token, Monolog\Handler\HipChatHandler\$version, and Monolog\Handler\HipChatHandler\validateStringLength().

99  {
100  if ($version == self::API_V1 && !$this->validateStringLength($name, static::MAXIMUM_NAME_LENGTH)) {
101  throw new \InvalidArgumentException('The supplied name is too long. HipChat\'s v1 API supports names up to 15 UTF-8 characters.');
102  }
103 
104  $connectionString = $useSSL ? 'ssl://'.$host.':443' : $host.':80';
105  parent::__construct($connectionString, $level, $bubble);
106 
107  $this->token = $token;
108  $this->name = $name;
109  $this->notify = $notify;
110  $this->room = $room;
111  $this->format = $format;
112  $this->host = $host;
113  $this->version = $version;
114  }
validateStringLength($str, $length)
Validates the length of a string.
+ Here is the call graph for this function:

Member Function Documentation

◆ buildContent()

Monolog\Handler\HipChatHandler::buildContent (   $record)
private

Builds the body of API call.

Parameters
array$record
Returns
string

Definition at line 135 of file HipChatHandler.php.

References Monolog\Handler\HipChatHandler\$room, Monolog\Handler\HipChatHandler\getAlertColor(), and Monolog\Handler\HipChatHandler\validateStringLength().

Referenced by Monolog\Handler\HipChatHandler\generateDataStream().

136  {
137  $dataArray = array(
138  'notify' => $this->version == self::API_V1 ?
139  ($this->notify ? 1 : 0) :
140  ($this->notify ? 'true' : 'false'),
141  'message' => $record['formatted'],
142  'message_format' => $this->format,
143  'color' => $this->getAlertColor($record['level']),
144  );
145 
146  if (!$this->validateStringLength($dataArray['message'], static::MAXIMUM_MESSAGE_LENGTH)) {
147  if (function_exists('mb_substr')) {
148  $dataArray['message'] = mb_substr($dataArray['message'], 0, static::MAXIMUM_MESSAGE_LENGTH).' [truncated]';
149  } else {
150  $dataArray['message'] = substr($dataArray['message'], 0, static::MAXIMUM_MESSAGE_LENGTH).' [truncated]';
151  }
152  }
153 
154  // if we are using the legacy API then we need to send some additional information
155  if ($this->version == self::API_V1) {
156  $dataArray['room_id'] = $this->room;
157  }
158 
159  // append the sender name if it is set
160  // always append it if we use the v1 api (it is required in v1)
161  if ($this->version == self::API_V1 || $this->name !== null) {
162  $dataArray['from'] = (string) $this->name;
163  }
164 
165  return http_build_query($dataArray);
166  }
getAlertColor($level)
Assigns a color to each level of log records.
validateStringLength($str, $length)
Validates the length of a string.
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ buildHeader()

Monolog\Handler\HipChatHandler::buildHeader (   $content)
private

Builds the header of the API Call.

Parameters
string$content
Returns
string

Definition at line 174 of file HipChatHandler.php.

References $header, and Monolog\Handler\HipChatHandler\$room.

Referenced by Monolog\Handler\HipChatHandler\generateDataStream().

175  {
176  if ($this->version == self::API_V1) {
177  $header = "POST /v1/rooms/message?format=json&auth_token={$this->token} HTTP/1.1\r\n";
178  } else {
179  // needed for rooms with special (spaces, etc) characters in the name
180  $room = rawurlencode($this->room);
181  $header = "POST /v2/room/{$room}/notification?auth_token={$this->token} HTTP/1.1\r\n";
182  }
183 
184  $header .= "Host: {$this->host}\r\n";
185  $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
186  $header .= "Content-Length: " . strlen($content) . "\r\n";
187  $header .= "\r\n";
188 
189  return $header;
190  }
+ Here is the caller graph for this function:

◆ combineRecords()

Monolog\Handler\HipChatHandler::combineRecords (   $records)
private

Combines multiple records into one.

Error level of the combined record will be the highest level from the given records. Datetime will be taken from the first record.

Parameters
$records
Returns
array

Definition at line 274 of file HipChatHandler.php.

References Monolog\Handler\AbstractHandler\$level, $messages, $records, Monolog\Handler\AbstractHandler\getFormatter(), PHP_EOL, Monolog\Handler\AbstractProcessingHandler\processRecord(), and Monolog\Handler\HipChatHandler\validateStringLength().

Referenced by Monolog\Handler\HipChatHandler\handleBatch().

275  {
276  $batchRecord = null;
277  $batchRecords = array();
278  $messages = array();
279  $formattedMessages = array();
280  $level = 0;
281  $levelName = null;
282  $datetime = null;
283 
284  foreach ($records as $record) {
285  $record = $this->processRecord($record);
286 
287  if ($record['level'] > $level) {
288  $level = $record['level'];
289  $levelName = $record['level_name'];
290  }
291 
292  if (null === $datetime) {
293  $datetime = $record['datetime'];
294  }
295 
296  $messages[] = $record['message'];
297  $messageStr = implode(PHP_EOL, $messages);
298  $formattedMessages[] = $this->getFormatter()->format($record);
299  $formattedMessageStr = implode('', $formattedMessages);
300 
301  $batchRecord = array(
302  'message' => $messageStr,
303  'formatted' => $formattedMessageStr,
304  'context' => array(),
305  'extra' => array(),
306  );
307 
308  if (!$this->validateStringLength($batchRecord['formatted'], static::MAXIMUM_MESSAGE_LENGTH)) {
309  // Pop the last message and implode the remaining messages
310  $lastMessage = array_pop($messages);
311  $lastFormattedMessage = array_pop($formattedMessages);
312  $batchRecord['message'] = implode(PHP_EOL, $messages);
313  $batchRecord['formatted'] = implode('', $formattedMessages);
314 
315  $batchRecords[] = $batchRecord;
316  $messages = array($lastMessage);
317  $formattedMessages = array($lastFormattedMessage);
318 
319  $batchRecord = null;
320  }
321  }
322 
323  if (null !== $batchRecord) {
324  $batchRecords[] = $batchRecord;
325  }
326 
327  // Set the max level and datetime for all records
328  foreach ($batchRecords as &$batchRecord) {
329  $batchRecord = array_merge(
330  $batchRecord,
331  array(
332  'level' => $level,
333  'level_name' => $levelName,
334  'datetime' => $datetime,
335  )
336  );
337  }
338 
339  return $batchRecords;
340  }
PHP_EOL
Definition: complexTest.php:5
$records
Definition: simple_test.php:22
$messages
Definition: en.php:5
getFormatter()
{Gets the formatter.FormatterInterface}
processRecord(array $record)
Processes a record.
validateStringLength($str, $length)
Validates the length of a string.
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ finalizeWrite()

Monolog\Handler\HipChatHandler::finalizeWrite ( )
protected

Finalizes the request by reading some bytes and then closing the socket.

If we do not read some but close the socket too early, hipchat sometimes drops the request entirely.

Definition at line 231 of file HipChatHandler.php.

References $res, Monolog\Handler\SocketHandler\closeSocket(), and Monolog\Handler\SocketHandler\getResource().

Referenced by Monolog\Handler\HipChatHandler\write().

232  {
233  $res = $this->getResource();
234  if (is_resource($res)) {
235  @fread($res, 2048);
236  }
237  $this->closeSocket();
238  }
foreach($_POST as $key=> $value) $res
closeSocket()
Close socket, if open.
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ generateDataStream()

Monolog\Handler\HipChatHandler::generateDataStream (   $record)
protected

{}

Parameters
array$record
Returns
string

Definition at line 122 of file HipChatHandler.php.

References Monolog\Handler\HipChatHandler\buildContent(), and Monolog\Handler\HipChatHandler\buildHeader().

123  {
124  $content = $this->buildContent($record);
125 
126  return $this->buildHeader($content) . $content;
127  }
buildHeader($content)
Builds the header of the API Call.
buildContent($record)
Builds the body of API call.
+ Here is the call graph for this function:

◆ getAlertColor()

Monolog\Handler\HipChatHandler::getAlertColor (   $level)
protected

Assigns a color to each level of log records.

Parameters
int$level
Returns
string

Definition at line 198 of file HipChatHandler.php.

References Monolog\Handler\AbstractHandler\$level, Monolog\Logger\DEBUG, Monolog\Logger\ERROR, Monolog\Logger\INFO, and Monolog\Logger\WARNING.

Referenced by Monolog\Handler\HipChatHandler\buildContent().

199  {
200  switch (true) {
201  case $level >= Logger::ERROR:
202  return 'red';
203  case $level >= Logger::WARNING:
204  return 'yellow';
205  case $level >= Logger::INFO:
206  return 'green';
207  case $level == Logger::DEBUG:
208  return 'gray';
209  default:
210  return 'yellow';
211  }
212  }
const DEBUG
Detailed debug information.
Definition: Logger.php:33
const ERROR
Runtime errors.
Definition: Logger.php:58
const WARNING
Exceptional occurrences that are not errors.
Definition: Logger.php:53
const INFO
Interesting events.
Definition: Logger.php:40
+ Here is the caller graph for this function:

◆ handleBatch()

Monolog\Handler\HipChatHandler::handleBatch ( array  $records)

{Handles a set of records at once.

Parameters
array$recordsThe records to handle (an array of record arrays)
}

Implements Monolog\Handler\HandlerInterface.

Definition at line 243 of file HipChatHandler.php.

References Monolog\Handler\AbstractHandler\$bubble, Monolog\Handler\HipChatHandler\combineRecords(), Monolog\Handler\AbstractHandler\isHandling(), and Monolog\Handler\HipChatHandler\write().

244  {
245  if (count($records) == 0) {
246  return true;
247  }
248 
249  $batchRecords = $this->combineRecords($records);
250 
251  $handled = false;
252  foreach ($batchRecords as $batchRecord) {
253  if ($this->isHandling($batchRecord)) {
254  $this->write($batchRecord);
255  $handled = true;
256  }
257  }
258 
259  if (!$handled) {
260  return false;
261  }
262 
263  return false === $this->bubble;
264  }
$records
Definition: simple_test.php:22
isHandling(array $record)
{Checks whether the given record will be handled by this handler.This is mostly done for performance ...
combineRecords($records)
Combines multiple records into one.
+ Here is the call graph for this function:

◆ validateStringLength()

Monolog\Handler\HipChatHandler::validateStringLength (   $str,
  $length 
)
private

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.

Parameters
string$str
int$length
Returns
bool

Definition at line 357 of file HipChatHandler.php.

Referenced by Monolog\Handler\HipChatHandler\__construct(), Monolog\Handler\HipChatHandler\buildContent(), and Monolog\Handler\HipChatHandler\combineRecords().

358  {
359  if (function_exists('mb_strlen')) {
360  return (mb_strlen($str) <= $length);
361  }
362 
363  return (strlen($str) <= $length);
364  }
+ Here is the caller graph for this function:

◆ write()

Monolog\Handler\HipChatHandler::write ( array  $record)
protected

{}

Parameters
array$record

Definition at line 219 of file HipChatHandler.php.

References Monolog\Handler\HipChatHandler\finalizeWrite(), and Sabre\VObject\write().

Referenced by Monolog\Handler\HipChatHandler\handleBatch().

220  {
221  parent::write($record);
222  $this->finalizeWrite();
223  }
finalizeWrite()
Finalizes the request by reading some bytes and then closing the socket.
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

Field Documentation

◆ $format

Monolog\Handler\HipChatHandler::$format
private

Definition at line 74 of file HipChatHandler.php.

Referenced by Monolog\Handler\HipChatHandler\__construct().

◆ $host

Monolog\Handler\HipChatHandler::$host
private

Definition at line 79 of file HipChatHandler.php.

Referenced by Monolog\Handler\HipChatHandler\__construct().

◆ $name

Monolog\Handler\HipChatHandler::$name
private

Definition at line 64 of file HipChatHandler.php.

Referenced by Monolog\Handler\HipChatHandler\__construct().

◆ $notify

Monolog\Handler\HipChatHandler::$notify
private

Definition at line 69 of file HipChatHandler.php.

Referenced by Monolog\Handler\HipChatHandler\__construct().

◆ $room

◆ $token

Monolog\Handler\HipChatHandler::$token
private

Definition at line 54 of file HipChatHandler.php.

Referenced by Monolog\Handler\HipChatHandler\__construct().

◆ $version

Monolog\Handler\HipChatHandler::$version
private

Definition at line 84 of file HipChatHandler.php.

Referenced by Monolog\Handler\HipChatHandler\__construct().

◆ API_V1

const Monolog\Handler\HipChatHandler::API_V1 = 'v1'

Use API version 1.

Definition at line 34 of file HipChatHandler.php.

◆ API_V2

const Monolog\Handler\HipChatHandler::API_V2 = 'v2'

Use API version v2.

Definition at line 39 of file HipChatHandler.php.

◆ MAXIMUM_MESSAGE_LENGTH

const Monolog\Handler\HipChatHandler::MAXIMUM_MESSAGE_LENGTH = 9500

The maximum allowed length for the message.

Definition at line 49 of file HipChatHandler.php.

◆ MAXIMUM_NAME_LENGTH

const Monolog\Handler\HipChatHandler::MAXIMUM_NAME_LENGTH = 15

The maximum allowed length for the name used in the "from" field.

Definition at line 44 of file HipChatHandler.php.


The documentation for this class was generated from the following file: