-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Add MS Teams webhook handler #2002
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Seb33300
wants to merge
2
commits into
Seldaek:main
Choose a base branch
from
Seb33300:ms-teams-handler
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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()