Skip to content

Commit 30ce44e

Browse files
authored
feat: global logs context (apache#26418)
1 parent 5c1e13e commit 30ce44e

File tree

5 files changed

+341
-2
lines changed

5 files changed

+341
-2
lines changed

superset/commands/report/execute.py

+2
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@
7171
from superset.utils.celery import session_scope
7272
from superset.utils.core import HeaderDataType, override_user
7373
from superset.utils.csv import get_chart_csv_data, get_chart_dataframe
74+
from superset.utils.decorators import logs_context
7475
from superset.utils.screenshots import ChartScreenshot, DashboardScreenshot
7576
from superset.utils.urls import get_url_path
7677

@@ -81,6 +82,7 @@ class BaseReportState:
8182
current_states: list[ReportState] = []
8283
initial: bool = False
8384

85+
@logs_context()
8486
def __init__(
8587
self,
8688
session: Session,

superset/reports/notifications/slack.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
import backoff
2424
import pandas as pd
25+
from flask import g
2526
from flask_babel import gettext as __
2627
from slack_sdk import WebClient
2728
from slack_sdk.errors import (
@@ -175,6 +176,7 @@ def send(self) -> None:
175176
channel = self._get_channel()
176177
body = self._get_body()
177178
file_type = "csv" if self._content.csv else "png"
179+
global_logs_context = getattr(g, "logs_context", {}) or {}
178180
try:
179181
token = app.config["SLACK_API_TOKEN"]
180182
if callable(token):
@@ -192,7 +194,12 @@ def send(self) -> None:
192194
)
193195
else:
194196
client.chat_postMessage(channel=channel, text=body)
195-
logger.info("Report sent to slack")
197+
logger.info(
198+
"Report sent to slack",
199+
extra={
200+
"execution_id": global_logs_context.get("execution_id"),
201+
},
202+
)
196203
except (
197204
BotUserAccessError,
198205
SlackRequestError,

superset/utils/decorators.py

+81-1
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,20 @@
1616
# under the License.
1717
from __future__ import annotations
1818

19+
import logging
1920
import time
2021
from collections.abc import Iterator
2122
from contextlib import contextmanager
2223
from typing import Any, Callable, TYPE_CHECKING
24+
from uuid import UUID
2325

24-
from flask import current_app, Response
26+
from flask import current_app, g, Response
2527

2628
from superset.utils import core as utils
2729
from superset.utils.dates import now_as_float
2830

31+
logger = logging.getLogger(__name__)
32+
2933
if TYPE_CHECKING:
3034
from superset.stats_logger import BaseStatsLogger
3135

@@ -61,6 +65,82 @@ def wrapped(*args: Any, **kwargs: Any) -> Any:
6165
return decorate
6266

6367

68+
def logs_context(
69+
context_func: Callable[..., dict[Any, Any]] | None = None,
70+
**ctx_kwargs: int | str | UUID | None,
71+
) -> Callable[..., Any]:
72+
"""
73+
Takes arguments and adds them to the global logs_context.
74+
This is for logging purposes only and values should not be relied on or mutated
75+
"""
76+
77+
def decorate(f: Callable[..., Any]) -> Callable[..., Any]:
78+
def wrapped(*args: Any, **kwargs: Any) -> Any:
79+
if not hasattr(g, "logs_context"):
80+
g.logs_context = {}
81+
82+
# limit data that can be saved to logs_context
83+
# in order to prevent antipatterns
84+
available_logs_context_keys = [
85+
"slice_id",
86+
"dashboard_id",
87+
"dataset_id",
88+
"execution_id",
89+
"report_schedule_id",
90+
]
91+
# set value from kwargs from
92+
# wrapper function if it exists
93+
# e.g. @logs_context()
94+
# def my_func(slice_id=None, **kwargs)
95+
#
96+
# my_func(slice_id=2)
97+
logs_context_data = {
98+
key: val
99+
for key, val in kwargs.items()
100+
if key in available_logs_context_keys
101+
if val is not None
102+
}
103+
104+
try:
105+
# if keys are passed in to decorator directly, add them to logs_context
106+
# by overriding values from kwargs
107+
# e.g. @logs_context(slice_id=1, dashboard_id=1)
108+
logs_context_data.update(
109+
{
110+
key: ctx_kwargs.get(key)
111+
for key in available_logs_context_keys
112+
if ctx_kwargs.get(key) is not None
113+
}
114+
)
115+
116+
if context_func is not None:
117+
# if a context function is passed in, call it and add the
118+
# returned values to logs_context
119+
# context_func=lambda *args, **kwargs: {
120+
# "slice_id": 1, "dashboard_id": 1
121+
# }
122+
logs_context_data.update(
123+
{
124+
key: value
125+
for key, value in context_func(*args, **kwargs).items()
126+
if key in available_logs_context_keys
127+
if value is not None
128+
}
129+
)
130+
131+
except (TypeError, KeyError, AttributeError):
132+
# do nothing if the key doesn't exist
133+
# or context is not callable
134+
logger.warning("Invalid data was passed to the logs context decorator")
135+
136+
g.logs_context.update(logs_context_data)
137+
return f(*args, **kwargs)
138+
139+
return wrapped
140+
141+
return decorate
142+
143+
64144
@contextmanager
65145
def stats_timing(stats_key: str, stats_logger: BaseStatsLogger) -> Iterator[float]:
66146
"""Provide a transactional scope around a series of operations."""
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# Licensed to the Apache Software Foundation (ASF) under one
2+
# or more contributor license agreements. See the NOTICE file
3+
# distributed with this work for additional information
4+
# regarding copyright ownership. The ASF licenses this file
5+
# to you under the Apache License, Version 2.0 (the
6+
# "License"); you may not use this file except in compliance
7+
# with the License. You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing,
12+
# software distributed under the License is distributed on an
13+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
# KIND, either express or implied. See the License for the
15+
# specific language governing permissions and limitations
16+
# under the License.
17+
import uuid
18+
from unittest.mock import MagicMock, patch
19+
20+
import pandas as pd
21+
from flask import g
22+
23+
24+
@patch("superset.reports.notifications.slack.g")
25+
@patch("superset.reports.notifications.slack.logger")
26+
def test_send_slack(
27+
logger_mock: MagicMock,
28+
flask_global_mock: MagicMock,
29+
) -> None:
30+
# `superset.models.helpers`, a dependency of following imports,
31+
# requires app context
32+
from superset.reports.models import ReportRecipients, ReportRecipientType
33+
from superset.reports.notifications.base import NotificationContent
34+
from superset.reports.notifications.slack import SlackNotification, WebClient
35+
36+
execution_id = uuid.uuid4()
37+
flask_global_mock.logs_context = {"execution_id": execution_id}
38+
content = NotificationContent(
39+
name="test alert",
40+
header_data={
41+
"notification_format": "PNG",
42+
"notification_type": "Alert",
43+
"owners": [1],
44+
"notification_source": None,
45+
"chart_id": None,
46+
"dashboard_id": None,
47+
},
48+
embedded_data=pd.DataFrame(
49+
{
50+
"A": [1, 2, 3],
51+
"B": [4, 5, 6],
52+
"C": ["111", "222", '<a href="http://www.example.com">333</a>'],
53+
}
54+
),
55+
description='<p>This is <a href="#">a test</a> alert</p><br />',
56+
)
57+
with patch.object(
58+
WebClient, "chat_postMessage", return_value=True
59+
) as chat_post_message_mock:
60+
SlackNotification(
61+
recipient=ReportRecipients(
62+
type=ReportRecipientType.SLACK,
63+
recipient_config_json='{"target": "some_channel"}',
64+
),
65+
content=content,
66+
).send()
67+
logger_mock.info.assert_called_with(
68+
"Report sent to slack", extra={"execution_id": execution_id}
69+
)
70+
chat_post_message_mock.assert_called_with(
71+
channel="some_channel",
72+
text="""*test alert*
73+
74+
<p>This is <a href="#">a test</a> alert</p><br />
75+
76+
<None|Explore in Superset>
77+
78+
```
79+
| | A | B | C |
80+
|---:|----:|----:|:-----------------------------------------|
81+
| 0 | 1 | 4 | 111 |
82+
| 1 | 2 | 5 | 222 |
83+
| 2 | 3 | 6 | <a href="http://www.example.com">333</a> |
84+
```
85+
""",
86+
)

0 commit comments

Comments
 (0)