Skip to content

Commit 5281dfa

Browse files
Merge pull request #457 from supertokens/feat/use-flag-for-logging
feat: added debug flag in the SuperTokenConfig in the init() for logging
2 parents d6dd603 + c1bdfae commit 5281dfa

File tree

7 files changed

+147
-15
lines changed

7 files changed

+147
-15
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
88

99
## [unreleased]
1010

11+
## [0.16.7] - 2023-11-2
12+
13+
- Added `debug` flag in `init()`. If set to `True`, debug logs will be printed.
14+
1115
## [0.16.6] - 2023-10-24
1216

1317
- Fixed server error in `sign_in_up` API

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: 10 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,8 @@ def __init__(
165170
mode,
166171
)
167172
self.supertokens_config = supertokens_config
173+
if debug is True:
174+
enable_debug_logging()
168175
self._telemetry_status: str = "NONE"
169176
log_debug_message(
170177
"Started SuperTokens with debug logging (supertokens.init called)"
@@ -217,6 +224,7 @@ def init(
217224
recipe_list: List[Callable[[AppInfo], RecipeModule]],
218225
mode: Optional[Literal["asgi", "wsgi"]],
219226
telemetry: Optional[bool],
227+
debug: Optional[bool],
220228
):
221229
if Supertokens.__instance is None:
222230
Supertokens.__instance = Supertokens(
@@ -226,6 +234,7 @@ def init(
226234
recipe_list,
227235
mode,
228236
telemetry,
237+
debug,
229238
)
230239
PostSTInitCallbacks.run_post_init_callbacks()
231240

tests/test_logger.py

Lines changed: 123 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,48 @@
1+
import importlib
12
import json
3+
import logging
4+
import os
5+
import sys
26
from datetime import datetime as real_datetime
37
from unittest import TestCase
48
from unittest.mock import MagicMock, patch
59

10+
import pytest
11+
12+
from supertokens_python import InputAppInfo, SupertokensConfig, init
613
from supertokens_python.constants import VERSION
7-
from supertokens_python.logger import log_debug_message, streamFormatter
14+
from supertokens_python.logger import (
15+
log_debug_message,
16+
streamFormatter,
17+
NAMESPACE,
18+
enable_debug_logging,
19+
)
20+
from supertokens_python.recipe import session
21+
22+
from tests.utils import clean_st, reset, setup_st, start_st
823

924

1025
class LoggerTests(TestCase):
26+
@pytest.fixture(autouse=True)
27+
def inject_fixtures(self, caplog: pytest.LogCaptureFixture):
28+
# caplog is the pytest fixture to capture all logs
29+
self._caplog = caplog # pylint: disable=attribute-defined-outside-init
30+
31+
def setup_method(self, _): # pylint: disable=no-self-use
32+
# Setting the log level to a higher level so debug logs are not printed
33+
logging.getLogger(NAMESPACE).setLevel(logging.ERROR)
34+
reset()
35+
clean_st()
36+
setup_st()
37+
38+
def teardown_method(self, _):
39+
self._caplog.clear()
40+
reset()
41+
clean_st()
42+
1143
@patch("supertokens_python.logger.datetime", wraps=real_datetime)
12-
def test_json_msg_format(self, datetime_mock: MagicMock):
44+
def test_1_json_msg_format(self, datetime_mock: MagicMock):
45+
enable_debug_logging()
1346
datetime_mock.utcnow.return_value = real_datetime(2000, 1, 1) # type: ignore
1447

1548
with self.assertLogs(level="DEBUG") as captured:
@@ -22,12 +55,98 @@ def test_json_msg_format(self, datetime_mock: MagicMock):
2255
"t": "2000-01-01T00:00Z",
2356
"sdkVer": VERSION,
2457
"message": "API replied with status 200",
25-
"file": "../tests/test_logger.py:16",
58+
"file": "../tests/test_logger.py:49",
2659
}
2760

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

0 commit comments

Comments
 (0)