Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/02-handlers-formatters-processors.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
- [_PushoverHandler_](https://github.com/Seldaek/monolog/blob/main/src/Monolog/Handler/PushoverHandler.php): Sends mobile notifications via the [Pushover](https://www.pushover.net/) API.
- [_SlackWebhookHandler_](https://github.com/Seldaek/monolog/blob/main/src/Monolog/Handler/SlackWebhookHandler.php): Logs records to a [Slack](https://www.slack.com/) account using Slack Webhooks.
- [_SlackHandler_](https://github.com/Seldaek/monolog/blob/main/src/Monolog/Handler/SlackHandler.php): Logs records to a [Slack](https://www.slack.com/) account using the Slack API (complex setup).
- [_TeamsWebhookHandler_](https://github.com/Seldaek/monolog/blob/main/src/Monolog/Handler/TeamsWebhookHandler.php): Logs records to a [MS Teams](https://www.microsoft.com/microsoft-teams) account using MS Teams Webhooks.
- [_SendGridHandler_](https://github.com/Seldaek/monolog/blob/main/src/Monolog/Handler/SendGridHandler.php): Sends emails via the SendGrid API.
- [_MandrillHandler_](https://github.com/Seldaek/monolog/blob/main/src/Monolog/Handler/MandrillHandler.php): Sends emails via the [`Mandrill API`](https://mandrillapp.com/api/docs/) using a [`Swift_Message`](http://swiftmailer.org/) instance.
- [_FleepHookHandler_](https://github.com/Seldaek/monolog/blob/main/src/Monolog/Handler/FleepHookHandler.php): Logs records to a [Fleep](https://fleep.io/) conversation using Webhooks.
Expand Down
6 changes: 1 addition & 5 deletions src/Monolog/Handler/Slack/SlackRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class SlackRecord
private bool $useAttachment;

/**
* Whether the the context/extra messages added to Slack as attachments are in a short style
* Whether the context/extra messages added to Slack as attachments are in a short style
*/
private bool $useShortAttachment;

Expand Down Expand Up @@ -97,10 +97,6 @@ public function __construct(
->includeContextAndExtra($includeContextAndExtra)
->excludeFields($excludeFields)
->setFormatter($formatter);

if ($this->includeContextAndExtra) {
$this->normalizerFormatter = new NormalizerFormatter();
}
Comment on lines -100 to -103
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is already done in ->includeContextAndExtra()

}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Monolog/Handler/SlackWebhookHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class SlackWebhookHandler extends AbstractProcessingHandler
* @param string|null $username Name of a bot
* @param bool $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise)
* @param string|null $iconEmoji The emoji name to use (or null)
* @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style
* @param bool $useShortAttachment Whether the context/extra messages added to Slack as attachments are in a short style
* @param bool $includeContextAndExtra Whether the attachment should include context and extra data
* @param string[] $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2']
*
Expand Down
267 changes: 267 additions & 0 deletions src/Monolog/Handler/Teams/TeamsPayload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,267 @@
<?php declare(strict_types=1);

/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Monolog\Handler\Teams;

use Monolog\Level;
use Monolog\Utils;
use Monolog\Formatter\NormalizerFormatter;
use Monolog\Formatter\FormatterInterface;
use Monolog\LogRecord;

/**
* MS Teams record utility helping to log to MS Teams webhooks.
*
* @author Sébastien Alfaiate <[email protected]>
* @see https://learn.microsoft.com/adaptive-cards/authoring-cards/getting-started
*
* @internal
*/
class TeamsPayload
{
public const COLOR_ATTENTION = 'attention';

public const COLOR_WARNING = 'warning';

public const COLOR_GOOD = 'good';

public const COLOR_DEFAULT = 'default';

private NormalizerFormatter $normalizerFormatter;

/**
* @param bool $includeContextAndExtra Whether the card should include context and extra data
* @param bool $formatMessage Whether the message should be formatted
* @param string[] $excludeFields Dot separated list of fields to exclude from MS Teams message. E.g. ['context.field1', 'extra.field2']
* @param string[] $toggleFields Dot separated list of fields to display with a toggle button in MS Teams message. E.g. ['context.field1', 'extra.field2']
*/
public function __construct(
private bool $includeContextAndExtra = false,
private bool $formatMessage = false,
private array $excludeFields = [],
private array $toggleFields = [],
) {
if ($this->includeContextAndExtra) {
$this->normalizerFormatter = new NormalizerFormatter();
}
}

/**
* Returns required data in format that MS Teams is expecting.
*
* @phpstan-return mixed[]
*/
public function getAdaptiveCardPayload(LogRecord $record, ?FormatterInterface $formatter = null): array
{
if ($formatter !== null && $this->formatMessage) {
$message = $formatter->format($record);
} else {
$message = $record->message;
}

$recordData = $this->removeExcludedFields($record);

$facts = $toggles = [];

$facts[] = $this->generateFactField('Level', $recordData['level_name']);

if ($this->includeContextAndExtra) {
foreach (['extra', 'context'] as $key) {
if (!isset($recordData[$key]) || \count($recordData[$key]) === 0) {
continue;
}

$data = $this->generateContextAndExtraFields($recordData[$key], $key);

$facts = array_merge($facts, $data['facts']);
$toggles = array_merge($toggles, $data['toggles']);
}
}

return [
'type' => 'message',
'attachments' => [
[
'contentType' => 'application/vnd.microsoft.card.adaptive',
'content' => [
'$schema' => 'http://adaptivecards.io/schemas/adaptive-card.json',
'type' => 'AdaptiveCard',
'version' => '1.5',
'body' => [
// Card Header
[
'type' => 'Container',
'style' => $this->getContainerStyle($record->level),
'items' => [
[
'type' => 'TextBlock',
'text' => $message,
'weight' => 'Bolder',
'size' => 'Medium',
'wrap' => true,
],
],
],
// Context and Extra
[
'type' => 'Container',
'spacing' => 'Medium',
'items' => [
[
'type' => 'FactSet',
'facts' => $facts,
],
],
]
],
// Toggles
'actions' => $toggles,
],
],
],
];
}

/**
* Returns MS Teams container style associated with provided level.
*/
private function getContainerStyle(Level $level): string
{
return match ($level) {
Level::Error, Level::Critical, Level::Alert, Level::Emergency => static::COLOR_ATTENTION,
Level::Warning => static::COLOR_WARNING,
Level::Info, Level::Notice => static::COLOR_GOOD,
Level::Debug => static::COLOR_DEFAULT
};
}

/**
* Stringifies an array of key/value pairs to be used in fact fields
*
* @param mixed[] $fields
*/
private function stringify(array $fields): string
{
/** @var array<array<mixed>|bool|float|int|string|null> $normalized */
$normalized = $this->normalizerFormatter->normalizeValue($fields);

$hasSecondDimension = \count(array_filter($normalized, 'is_array')) > 0;
$hasOnlyNonNumericKeys = \count(array_filter(array_keys($normalized), 'is_numeric')) === 0;

return $hasSecondDimension || $hasOnlyNonNumericKeys
? Utils::jsonEncode($normalized, JSON_PRETTY_PRINT|Utils::DEFAULT_JSON_FLAGS)
: Utils::jsonEncode($normalized, Utils::DEFAULT_JSON_FLAGS);
}

/**
* Generates fact field
*
* @param string|mixed[] $value
*
* @return array{title: string, value: string}
*/
private function generateFactField(string $title, $value): array
{
$value = \is_array($value)
? substr($this->stringify($value), 0, 1990)
: $value;

return [
'title' => ucfirst($title),
'value' => $value,
];
}

/**
* Generates fact field
*
* @param string|mixed[] $value
*
* @return array{type: string, title: string, card: array{type: string, body: array<array{type: string, text: string, wrap: bool}>}}
*/
private function generateToggleField(string $title, $value): array
{
$value = \is_array($value)
? substr($this->stringify($value), 0, 19990)
: $value;

return [
'type' => 'Action.ShowCard',
'title' => ucfirst($title),
'card' => [
'type' => 'AdaptiveCard',
'body' => [
[
'type' => 'TextBlock',
'text' => $value,
'wrap' => true,
],
],
],
];
}

/**
* Generates a collection of fact fields from array
*
* @param mixed[] $data
*
* @return array{facts: array<array{title: string, value: string}>, toggles: array<array{type: string, title: string, card: array{type: string, body: array<array{type: string, text: string, wrap: bool}>}}>}
*/
private function generateContextAndExtraFields(array $data, string $type): array
{
/** @var array<array<mixed>|string> $normalized */
$normalized = $this->normalizerFormatter->normalizeValue($data);

$fields = [
'facts' => [],
'toggles' => [],
];

foreach ($normalized as $key => $value) {
if (in_array($type.'.'.$key, $this->toggleFields, true)) {
$fields['toggles'][] = $this->generateToggleField((string) $key, $value);
} else {
$fields['facts'][] = $this->generateFactField((string) $key, $value);
}
}

return $fields;
}

/**
* Get a copy of record with fields excluded according to $this->excludeFields
*
* @return mixed[]
*/
private function removeExcludedFields(LogRecord $record): array
{
$recordData = $record->toArray();

foreach ($this->excludeFields as $field) {
$keys = explode('.', $field);
$node = &$recordData;
$lastKey = end($keys);
foreach ($keys as $key) {
if (!isset($node[$key])) {
break;
}
if ($lastKey === $key) {
unset($node[$key]);
break;
}
$node = &$node[$key];
}
}

return $recordData;
}
}
94 changes: 94 additions & 0 deletions src/Monolog/Handler/TeamsWebhookHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php declare(strict_types=1);

/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Monolog\Handler;

use Monolog\Level;
use Monolog\Utils;
use Monolog\Handler\Teams\TeamsPayload;
use Monolog\LogRecord;

/**
* Sends notifications through MS Teams Webhooks
*
* @author Sébastien Alfaiate <[email protected]>
* @see https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook
* @see https://support.microsoft.com/office/create-incoming-webhooks-with-workflows-for-microsoft-teams-8ae491c7-0394-4861-ba59-055e33f75498
*/
class TeamsWebhookHandler extends AbstractProcessingHandler
{
/**
* MS Teams Webhook URL.
*
* @var non-empty-string
*/
private string $webhookUrl;

/**
* Instance of the TeamsPayload util class preparing data for MS Teams API.
*/
private TeamsPayload $teamsPayload;

/**
* @param non-empty-string $webhookUrl MS Teams Webhook URL
* @param bool $includeContextAndExtra Whether the card should include context and extra data
* @param string[] $excludeFields Dot separated list of fields to exclude from MS Teams message. E.g. ['context.field1', 'extra.field2']
* @param string[] $toggleFields Dot separated list of fields to display with a toggle button in MS Teams message. E.g. ['context.field1', 'extra.field2']
*
* @throws MissingExtensionException If the curl extension is missing
*/
public function __construct(
string $webhookUrl,
bool $includeContextAndExtra = false,
bool $formatMessage = false,
$level = Level::Critical,
bool $bubble = true,
array $excludeFields = [],
array $toggleFields = []
) {
if (!\extension_loaded('curl')) {
throw new MissingExtensionException('The curl extension is needed to use the TeamsWebhookHandler');
}

parent::__construct($level, $bubble);

$this->webhookUrl = $webhookUrl;

$this->teamsPayload = new TeamsPayload($includeContextAndExtra, $formatMessage, $excludeFields, $toggleFields);
}

public function getTeamsPayload(): TeamsPayload
{
return $this->teamsPayload;
}

/**
* @inheritDoc
*/
protected function write(LogRecord $record): void
{
$postData = $this->teamsPayload->getAdaptiveCardPayload($record, $this->getFormatter());
$postString = Utils::jsonEncode($postData);

$ch = curl_init();
$options = [
CURLOPT_URL => $this->webhookUrl,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-type: application/json'],
CURLOPT_POSTFIELDS => $postString,
];

curl_setopt_array($ch, $options);

Curl\Util::execute($ch);
}
}
Loading
Loading