Skip to content

Commit

Permalink
Merge pull request #5 from crazyfactory/fixes
Browse files Browse the repository at this point in the history
fix #2 (slack exec fail),
fix #3 (sentry extra ctx),
feat #4 (slack msg/icon/channel customization)
  • Loading branch information
adhocore authored Apr 25, 2017
2 parents b566c0f + b3d7c07 commit 8e22680
Show file tree
Hide file tree
Showing 10 changed files with 139 additions and 25 deletions.
6 changes: 6 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,11 @@
"sentry/sentry": "^1.6.2",
"phpunit/phpunit": "^5.7.0",
"mockery/mockery": "@stable"
},
"config": {
"optimize-autoloader": true,
"preferred-install": {
"*": "dist"
}
}
}
12 changes: 11 additions & 1 deletion examples/default.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,17 @@
// Set the request ID for current session, which is used by each of the registered loggers (only sentry has this feature ATM).
$logger->setRequestId($id);

$logger->special('slack:: test package phalcon-loggers ' . $id, ['mentions' => 'slackbot']);
$logger->special('slack:: test package phalcon-loggers ' . $id, [
'mentions' => 'channel',
'attachment' => [
'title' => 'Attachment title',
'text' => 'Attachment text',
'color' => 'good',
],
'username' => 'adhocore',
'channel' => '#general',
'icon_emoji' => ':+1:',
]);
// $logger->critical('sentry:: test package phalcon-loggers ' . $id);

// Give back the feedback to user.
Expand Down
27 changes: 24 additions & 3 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
## phalcon-loggers
## phalcon-loggers ![build status](https://api.travis-ci.org/crazyfactory/phalcon-loggers.svg?branch=master)

A collection of configurable logging adapters with logging functionality loosely PSR compatible for phalcon 3.x and PHP 7.x.
Currently the following adapters are implemented:
Expand Down Expand Up @@ -56,9 +56,30 @@ $di->getShared('logger')->info('some text');
// Supports interpolation for keys wrapped in curly brace.
$di->getShared('logger')->critical('some text {key}', ['key' => 'val']);

//
// Below examples assume that info level is allowed in config->slack->levels array.
//
// Mention an user in slack:
$di->getShared('slack')->info('some text {a}', ['mentions' => 'slackbot', 'a' => 10]);

$context = ['mentions' => 'slackbot', 'a' => 10];
$di->getShared('slack')->info('some text {a}', $context);

// Customize channel, username, icon_emoji, icon_url via context:
$context += [
'username' => 'bot',
'channel' => '#general',
'icon_emoji' => ':monkey_face:',
];
$di->getShared('slack')->info('some other text {a}', $context);

// Attachment:
$context += [
'attachment' => [
'title' => 'Attachment title',
'text' => 'Attachment text',
'color' => 'good',
],
];
$di->getShared('slack')->info('yet other text {a} with attachment', $context);
```

See [examples](examples/) for details and various integration samples.
Expand Down
6 changes: 6 additions & 0 deletions src/Adapter/Sentry.php
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,12 @@ protected function send($loggable, int $type, array $context = [])

$context += ['level' => static::toSentryLogLevel($type)];

// Wipe out extraneous keys. Issue #3.
$context = array_intersect_key($context, array_flip([
'context', 'extra', 'fingerprint', 'level',
'logger', 'release', 'tags',
]));

// Tag current request ID for search/trace.
if ($this->requestId) {
$this->client->tags_context(['request' => $this->requestId]);
Expand Down
35 changes: 30 additions & 5 deletions src/Adapter/Slack.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ public function __construct($config)
*/
public function logInternal($message, $type, $time, array $context = [])
{
$context += compact('time', 'type');

// Send if web hook is configured and the desired log level is met.
if ($this->shouldSend($type)) {
$this->eventCount++;
Expand Down Expand Up @@ -83,11 +85,34 @@ public function preparePayload(string $message, array $context = []) : string
$appName = "*{$appName}@{$this->config->environment}*";
}

return json_encode([
'mrkdwn' => true,
'link_names' => true,
'text' => "{$appName}{$mentions}\n{$message}",
], JSON_UNESCAPED_UNICODE);
$payload = isset($this->config->slack->context)
? $this->config->slack->context->toArray()
: [];

$payload += ['text' => "{$appName}{$mentions}\n{$message}"];

// Attachment.
if (!empty($context['attachment']) && is_array($context['attachment'])) {
$colors = isset($this->config->slack->colors)
? $this->config->slack->colors->toArray()
: [];

$payload['attachments'] = [$context['attachment'] + [
'color' => $colors[$context['type'] ?? -1] ?? '#e3e4e6',
'fallback' => $message,
'mrkdwn_in' => ['fields'],
'text' => $message,
'ts' => $context['time'] ?? time(),
]];
}

foreach (['channel', 'icon_url', 'icon_emoji', 'username'] as $key) {
if (!empty($context[$key])) {
$payload[$key] = $context[$key];
}
}

return json_encode($payload, JSON_UNESCAPED_UNICODE);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Multiple.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public function logException(\Throwable $exception, array $context = [], int $ty
'message' => $exception->getMessage(),
];

$logger->log($type, "{class}#{code} with message '{message}' thrown at {file}:{line}", $context);
$logger->log($type, "{class}#{code} with message `{message}` thrown at {file}:{line}", $context);
}
}

Expand Down
20 changes: 20 additions & 0 deletions src/config.logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,5 +68,25 @@
\Phalcon\Logger::SPECIAL,
\Phalcon\Logger::CUSTOM,
],

// The default context. Can be overridden with context parameter on each call to log:
// Eg: di->get('slack')->log(level, msg, overrideContext).
// Also supported: 'icon_emoji', 'icon_url' and 'username' contexts here.
'context' => [
'channel' => '#general',
'mrkdwn' => true,
'link_names' => true,
],

// Color map for attachments.
'colors' => [
\Phalcon\Logger::EMERGENCE => 'danger',
\Phalcon\Logger::CRITICAL => 'danger',
\Phalcon\Logger::ERROR => 'danger',
\Phalcon\Logger::ALERT => 'good',
\Phalcon\Logger::INFO => 'good',
\Phalcon\Logger::NOTICE => 'warning',
\Phalcon\Logger::WARNING => 'warning',
],
],
];
40 changes: 26 additions & 14 deletions tests/Adapter/SlackTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public function test_construct_throws_on_invalid_config()

public function test_logInternal_doesnot_log_when_env_is_not_whitelisted()
{
$config = require __DIR__ . '/../fixtures/config.logger.php';
$config = require __DIR__ . '/../fixtures/config.logger.php';
$config['slack']['environments'] = [];

($slack = new Slack($config))->logInternal(__METHOD__, Logger::SPECIAL, time());
Expand All @@ -61,7 +61,7 @@ public function test_logInternal_doesnot_log_when_webhook_not_set()

public function test_logInternal_doesnot_log_unspecified_levels()
{
$config = require __DIR__ . '/../fixtures/config.logger.php';
$config = require __DIR__ . '/../fixtures/config.logger.php';
$config['slack']['levels'] = [Logger::ERROR];

($slack = new Slack($config))->logInternal(__METHOD__, Logger::INFO, time());
Expand All @@ -71,9 +71,9 @@ public function test_logInternal_doesnot_log_unspecified_levels()

public function test_logInternal_logs_specified_levels()
{
$config = require __DIR__ . '/../fixtures/config.logger.php';
$config = require __DIR__ . '/../fixtures/config.logger.php';
$config['slack']['webhookUrl'] = 'dummy.url';
$config['slack']['levels'] = [Logger::CRITICAL];
$config['slack']['levels'] = [Logger::CRITICAL];

($slack = new Slack($config))->logInternal(__METHOD__, Logger::CRITICAL, time());
$this->assertSame(1, $slack->getEventCount(), 'one_event_should_have_been_logged');
Expand All @@ -93,15 +93,27 @@ public function preparePayloadTestcases()
return [
[
'hello {name}, this is a test',
['mentions' => 'slackbot,test', 'name' => 'there'],
['mentions' => 'slackbot,test', 'name' => 'there', 'attachment' => [
'title' => 'A',
'text' => 'apple',
'color' => 'good',
], 'type' => 8, 'time' => $t = time()],
[
'environment' => 'test',
'appName' => 'phalcon-loggers',
'slack' => ['context' => ['channel' => '#random']],
],
[
'mrkdwn' => true,
'link_names' => true,
'text' => "*phalcon-loggers@test* <@slackbot> <@test>\nhello there, this is a test",
'channel' => '#random',
'text' => "*phalcon-loggers@test* <@slackbot> <@test>\nhello there, this is a test",
'attachments' => [[
'title' => 'A',
'text' => 'apple',
'color' => 'good',
'fallback' => 'hello there, this is a test',
'mrkdwn_in' => ['fields'],
'ts' => $t,
]],
],
],
[
Expand All @@ -110,11 +122,11 @@ public function preparePayloadTestcases()
[
'environment' => 'test',
'appName' => '',
'slack' => ['context' => ['channel' => '#general']],
],
[
'mrkdwn' => true,
'link_names' => true,
'text' => " <@test>\nanother test",
'channel' => '#general',
'text' => " <@test>\nanother test",
],
],
[
Expand All @@ -123,11 +135,11 @@ public function preparePayloadTestcases()
[
'environment' => 'test',
'appName' => '',
'slack' => ['context' => ['mrkdwn' => false]],
],
[
'mrkdwn' => true,
'link_names' => true,
'text' => "\nanother test",
'mrkdwn' => false,
'text' => "\nanother test",
],
],
];
Expand Down
2 changes: 1 addition & 1 deletion tests/MultipleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function test_logException_calls_log_with_loglevel_error_when_logExceptio
$handler = m::mock('CrazyFactory\\PhalconLogger\\Adapter\\Slack')
->shouldReceive('log')->times(1)->andReturnUsing(function ($type, $messageTemplate) {
$this->assertSame(Logger::ERROR, $type);
$this->assertSame('{class}#{code} with message \'{message}\' thrown at {file}:{line}', $messageTemplate);
$this->assertSame('{class}#{code} with message `{message}` thrown at {file}:{line}', $messageTemplate);
})
;

Expand Down
14 changes: 14 additions & 0 deletions tests/fixtures/config.logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,20 @@
'curlMethod' => 'sync',
'headers' => [],
'levels' => [Logger::SPECIAL],
'context' => [
'channel' => '#general',
'mrkdwn' => true,
'link_names' => true,
],
'colors' => [
Logger::EMERGENCE => 'danger',
Logger::CRITICAL => 'danger',
Logger::ERROR => 'danger',
Logger::ALERT => 'good',
Logger::INFO => 'good',
Logger::NOTICE => 'warning',
Logger::WARNING => 'warning',
],
],
'sentry' => [
'credential' => [
Expand Down

0 comments on commit 8e22680

Please sign in to comment.