Skip to content

Commit afec359

Browse files
feat: added debug flag in the SuperTokenConfig in the init() for logging
1 parent d6dd603 commit afec359

File tree

6 files changed

+133
-12
lines changed

6 files changed

+133
-12
lines changed

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@
7070

7171
setup(
7272
name="supertokens_python",
73-
version="0.16.6",
73+
version="0.16.7",
7474
author="SuperTokens",
7575
license="Apache 2.0",
7676
author_email="[email protected]",

supertokens_python/__init__.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,14 +34,10 @@ def init(
3434
recipe_list: List[Callable[[supertokens.AppInfo], RecipeModule]],
3535
mode: Optional[Literal["asgi", "wsgi"]] = None,
3636
telemetry: Optional[bool] = None,
37+
debug: Optional[bool] = None,
3738
):
3839
return Supertokens.init(
39-
app_info,
40-
framework,
41-
supertokens_config,
42-
recipe_list,
43-
mode,
44-
telemetry,
40+
app_info, framework, supertokens_config, recipe_list, mode, telemetry, debug
4541
)
4642

4743

supertokens_python/constants.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from __future__ import annotations
1515

1616
SUPPORTED_CDI_VERSIONS = ["3.0"]
17-
VERSION = "0.16.6"
17+
VERSION = "0.16.7"
1818
TELEMETRY = "/telemetry"
1919
USER_COUNT = "/users/count"
2020
USER_DELETE = "/user/remove"

supertokens_python/logger.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
1212
# License for the specific language governing permissions and limitations
1313
# under the License.
14-
1514
import json
1615
import logging
1716
from datetime import datetime
@@ -25,11 +24,16 @@
2524

2625
supertokens_dir = path.dirname(__file__)
2726

27+
28+
def enable_debug_logging():
29+
_logger.setLevel(logging.DEBUG)
30+
31+
2832
# Configure logger
2933
_logger = logging.getLogger(NAMESPACE)
3034
debug_env = getenv(DEBUG_ENV_VAR, "").lower()
3135
if debug_env == "1":
32-
_logger.setLevel(logging.DEBUG)
36+
enable_debug_logging()
3337

3438

3539
def _get_log_timestamp() -> str:

supertokens_python/supertokens.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,11 @@
1919

2020
from typing_extensions import Literal
2121

22-
from supertokens_python.logger import get_maybe_none_as_str, log_debug_message
22+
from supertokens_python.logger import (
23+
get_maybe_none_as_str,
24+
log_debug_message,
25+
enable_debug_logging,
26+
)
2327

2428
from .constants import FDI_KEY_HEADER, RID_KEY_HEADER, USER_COUNT, USER_DELETE, USERS
2529
from .exceptions import SuperTokensError
@@ -150,6 +154,7 @@ def __init__(
150154
recipe_list: List[Callable[[AppInfo], RecipeModule]],
151155
mode: Optional[Literal["asgi", "wsgi"]],
152156
telemetry: Optional[bool],
157+
debug: Optional[bool],
153158
):
154159
if not isinstance(app_info, InputAppInfo): # type: ignore
155160
raise ValueError("app_info must be an instance of InputAppInfo")
@@ -165,6 +170,9 @@ def __init__(
165170
mode,
166171
)
167172
self.supertokens_config = supertokens_config
173+
self.debug = debug
174+
if debug is True:
175+
enable_debug_logging()
168176
self._telemetry_status: str = "NONE"
169177
log_debug_message(
170178
"Started SuperTokens with debug logging (supertokens.init called)"
@@ -217,6 +225,7 @@ def init(
217225
recipe_list: List[Callable[[AppInfo], RecipeModule]],
218226
mode: Optional[Literal["asgi", "wsgi"]],
219227
telemetry: Optional[bool],
228+
debug: Optional[bool],
220229
):
221230
if Supertokens.__instance is None:
222231
Supertokens.__instance = Supertokens(
@@ -226,6 +235,7 @@ def init(
226235
recipe_list,
227236
mode,
228237
telemetry,
238+
debug,
229239
)
230240
PostSTInitCallbacks.run_post_init_callbacks()
231241

tests/test_logger.py

Lines changed: 112 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,38 @@
1+
import importlib
12
import json
3+
import os
4+
import sys
25
from datetime import datetime as real_datetime
36
from unittest import TestCase
47
from unittest.mock import MagicMock, patch
58

9+
import pytest
10+
11+
from supertokens_python import InputAppInfo, SupertokensConfig, init
612
from supertokens_python.constants import VERSION
713
from supertokens_python.logger import log_debug_message, streamFormatter
14+
from supertokens_python.recipe import session
15+
16+
from tests.utils import clean_st, reset, setup_st, start_st
817

918

1019
class LoggerTests(TestCase):
20+
def setup_method(self, _):
21+
self._caplog.clear()
22+
reset()
23+
clean_st()
24+
setup_st()
25+
26+
def teardown_method(self, _):
27+
self._caplog.clear()
28+
reset()
29+
clean_st()
30+
31+
@pytest.fixture(autouse=True)
32+
def inject_fixtures(self, caplog: pytest.LogCaptureFixture):
33+
# caplog is the pytest fixture to capture all logs
34+
self._caplog = caplog # pylint: disable=attribute-defined-outside-init
35+
1136
@patch("supertokens_python.logger.datetime", wraps=real_datetime)
1237
def test_json_msg_format(self, datetime_mock: MagicMock):
1338
datetime_mock.utcnow.return_value = real_datetime(2000, 1, 1) # type: ignore
@@ -22,7 +47,7 @@ def test_json_msg_format(self, datetime_mock: MagicMock):
2247
"t": "2000-01-01T00:00Z",
2348
"sdkVer": VERSION,
2449
"message": "API replied with status 200",
25-
"file": "../tests/test_logger.py:16",
50+
"file": "../tests/test_logger.py:40",
2651
}
2752

2853
@staticmethod
@@ -31,3 +56,89 @@ def test_stream_formatter_format():
3156
streamFormatter._fmt # pylint: disable=protected-access
3257
== "{name} {message}\n"
3358
)
59+
60+
def test_logger_config_with_debug_true(self):
61+
start_st()
62+
init(
63+
supertokens_config=SupertokensConfig("http://localhost:3567"),
64+
app_info=InputAppInfo(
65+
app_name="SuperTokens Demo",
66+
api_domain="api.supertokens.io",
67+
website_domain="supertokens.io",
68+
api_base_path="/",
69+
),
70+
framework="fastapi",
71+
recipe_list=[session.init(anti_csrf="VIA_CUSTOM_HEADER")],
72+
debug=True,
73+
)
74+
75+
logMsg = "log test - valid log"
76+
log_debug_message(logMsg)
77+
78+
assert logMsg in self._caplog.text
79+
80+
def test_logger_config_with_debug_false(self):
81+
start_st()
82+
init(
83+
supertokens_config=SupertokensConfig("http://localhost:3567"),
84+
app_info=InputAppInfo(
85+
app_name="SuperTokens Demo",
86+
api_domain="api.supertokens.io",
87+
website_domain="supertokens.io",
88+
api_base_path="/",
89+
),
90+
framework="fastapi",
91+
recipe_list=[session.init(anti_csrf="VIA_CUSTOM_HEADER")],
92+
debug=False,
93+
)
94+
95+
logMsg = "log test - valid log"
96+
log_debug_message(logMsg)
97+
98+
assert logMsg not in self._caplog.text
99+
100+
def test_logger_config_with_debug_not_set(self):
101+
start_st()
102+
init(
103+
supertokens_config=SupertokensConfig("http://localhost:3567"),
104+
app_info=InputAppInfo(
105+
app_name="SuperTokens Demo",
106+
api_domain="api.supertokens.io",
107+
website_domain="supertokens.io",
108+
api_base_path="/",
109+
),
110+
framework="fastapi",
111+
recipe_list=[session.init(anti_csrf="VIA_CUSTOM_HEADER")],
112+
)
113+
114+
logMsg = "log test - valid log"
115+
log_debug_message(logMsg)
116+
117+
assert logMsg not in self._caplog.text
118+
119+
def test_logger_config_with_env_var(self):
120+
os.environ["SUPERTOKENS_DEBUG"] = "1"
121+
122+
# environment variable was already set when the logger module was imported
123+
# since its being changed for the test, the module needs to be reloaded.
124+
importlib.reload(sys.modules["supertokens_python.logger"])
125+
start_st()
126+
init(
127+
supertokens_config=SupertokensConfig("http://localhost:3567"),
128+
app_info=InputAppInfo(
129+
app_name="SuperTokens Demo",
130+
api_domain="api.supertokens.io",
131+
website_domain="supertokens.io",
132+
api_base_path="/",
133+
),
134+
framework="fastapi",
135+
recipe_list=[session.init(anti_csrf="VIA_CUSTOM_HEADER")],
136+
)
137+
138+
logMsg = "log test - valid log"
139+
log_debug_message(logMsg)
140+
141+
# Unset the environment variable
142+
del os.environ["SUPERTOKENS_DEBUG"]
143+
144+
assert logMsg in self._caplog.text

0 commit comments

Comments
 (0)