Skip to content

Commit

Permalink
Use comma in logger to separate context vars
Browse files Browse the repository at this point in the history
  • Loading branch information
igrek51 committed Jun 26, 2024
1 parent 15fac7e commit 33c54b7
Show file tree
Hide file tree
Showing 14 changed files with 54 additions and 37 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ coverage.xml

.idea
*.iml
launch.json
.vscode
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
.PHONY: setup test clean build dist
.PHONY: venv test clean build dist

PYTHON_INTERPRETER ?= python3
OUTPUT_README = README.md
SHELL := /bin/bash

setup:
venv:
python3 -m venv venv &&\
. venv/bin/activate &&\
pip install --upgrade pip setuptools &&\
Expand Down
2 changes: 1 addition & 1 deletion docs/example/inspection.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ class Person(BaseModel):


if __name__ == '__main__':
wat.short / Person(name='george')
wat.code / Person
2 changes: 1 addition & 1 deletion docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ python -m pip install -e .
## Testing
Running tests:
```bash
make setup
make venv
. venv/bin/activate
make test
```
8 changes: 4 additions & 4 deletions nuclear/inspection/inspection.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,8 @@ def _get_callable_signature(name: str, obj: Any) -> Optional[str]:
def _get_source_code(obj: Any) -> Optional[str]:
try:
return std_inspect.getsource(obj)
except (OSError, TypeError, IndentationError):
return None
except (OSError, TypeError, IndentationError) as e:
return f'failed to get source code: {type(e)}: {e}'


def _get_doc(obj: Any, long: bool) -> Optional[str]:
Expand Down Expand Up @@ -244,9 +244,9 @@ def _format_dict_value(dic: Dict, indent: int) -> str:
return f'{STYLE_YELLOW}{{}}{RESET}'


def _format_list_value(l: List, indent: int) -> str:
def _format_list_value(lst: List, indent: int) -> str:
lines: List[str] = []
for value in l:
for value in lst:
value_str = _format_value(value, indent)
lines.append(' ' * indent + f'{value_str},')
if lines:
Expand Down
2 changes: 1 addition & 1 deletion nuclear/sublog/context_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def __init__(self, context_message: str, cause: Optional[BaseException] = None,
self.__cause__ = cause

def __str__(self) -> str:
e: Exception = self
e: Optional[BaseException] = self
layers = []
while e is not None:
if isinstance(e, ContextError):
Expand Down
2 changes: 1 addition & 1 deletion nuclear/sublog/exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def exception_details(e: BaseException) -> str:
traceback_str = ', '.join(traceback_lines)
cause = _root_cause_type(e)
error_msg = _error_message(e)
return f'{error_msg}: cause={cause}, traceback={traceback_str}'
return f'{error_msg}, cause={cause}, traceback={traceback_str}'


def extended_exception_details(e: BaseException) -> Tuple[str, Dict]:
Expand Down
2 changes: 1 addition & 1 deletion nuclear/sublog/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def _print_log(self, message: str, ctx: Dict[str, Any], logger_func: Callable):
if display_context:
if message.endswith(':'):
message = message[:-1]
logger_func(f'{message}: {display_context}')
logger_func(f'{message}, {display_context}')
else:
logger_func(message)

Expand Down
2 changes: 1 addition & 1 deletion nuclear/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "2.2.1"
__version__ = "2.2.2"
3 changes: 2 additions & 1 deletion requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
pytest==7.1.2
pytest==8.2.2
mock==4.0.3
coverage==6.3.2
setuptools==67.6.0
Expand All @@ -8,3 +8,4 @@ mkdocs==1.4.0
mkdocs-material==8.5.6
backoff==2.0.1
pydantic==2.4.0
mypy==1.10.1
22 changes: 19 additions & 3 deletions tests/inspection/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from pydantic import BaseModel

from nuclear import CliBuilder, argument, wat
from nuclear.inspection.inspection import Wat, inspect_format
from nuclear.inspection.inspection import inspect_format
from tests.asserts import assert_multiline_match, strip_ansi_colors, StdoutCap


Expand Down Expand Up @@ -186,14 +186,30 @@ def test_inspect_datetime_repr():
''')


def test_inspect_source_code():
def test_inspect_long():
output = inspect_format(datetime, long=True, code=True)
lines = output.splitlines()
assert "value: <class 'datetime.datetime'>" in lines
assert "type: type" in lines
assert "signature: class datetime(…)" in lines
assert "datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])" in lines
assert "class datetime(date):" in lines


def test_inspect_source_code():
class Sorcerer:
def __init__(self):
self.level = 1
def level_up(self):
self.level += 1

output = inspect_format(Sorcerer, code=True)
lines = output.splitlines()
assert "value: <class 'test_inspect.test_inspect_source_code.<locals>.Sorcerer'>" in lines
assert "type: type" in lines
assert "signature: class Sorcerer()" in lines
assert "source code:" in lines
assert " class Sorcerer:" in lines
assert " self.level += 1" in lines


def test_inspect_async_def():
Expand Down
12 changes: 6 additions & 6 deletions tests/sublog/test_catch.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def test_sublog_traceback():
with add_context('liftoff', speed='zero'):
disaster()

mockio.assert_match_uncolor('ERROR initializing: liftoff: disaster: request_id=42 speed=zero '
mockio.assert_match_uncolor('ERROR initializing: liftoff: disaster, request_id=42 speed=zero '
'cause=RuntimeError '
'traceback="(.+)/test_catch.py:12, '
'(.+)/test_catch.py:22, '
Expand Down Expand Up @@ -43,7 +43,7 @@ def test_catch_with_context_name():
with error_handler('hacking time'):
raise RuntimeError('nope')

mockio.assert_match_uncolor('ERROR hacking time: nope: '
mockio.assert_match_uncolor('ERROR hacking time: nope, '
'cause=RuntimeError '
'traceback=(.+)/test_catch.py:44"?$')

Expand All @@ -56,7 +56,7 @@ def test_catch_chained_exception_cause():
except AttributeError as e:
raise RuntimeError('wrapper') from e

mockio.assert_match_uncolor('ERROR hacking time: wrapper: real cause: '
mockio.assert_match_uncolor('ERROR hacking time: wrapper: real cause, '
'cause=AttributeError '
'traceback=(.+)/test_catch.py:55"?$')

Expand All @@ -71,7 +71,7 @@ def test_recover_from_dynamically_imported_module():
assert loader is not None, 'no module loader'
loader.exec_module(ext_module)

mockio.assert_match_uncolor(r'ERROR hacking time: Fire!: '
mockio.assert_match_uncolor(r'ERROR hacking time: Fire!, '
r'cause=RuntimeError '
r'traceback="(.+)/test_catch.py:72, '
r'<frozen importlib._bootstrap_external>:\d+, '
Expand All @@ -87,7 +87,7 @@ def doit():
cli = CliBuilder(log_error=True, run=doit)
cli.run()

mockio.assert_match_uncolor('ERROR fail: '
mockio.assert_match_uncolor('ERROR fail, '
'cause=RuntimeError '
'traceback=(.+)/test_catch.py:85"?$')

Expand All @@ -99,6 +99,6 @@ def test_log_exception():
except Exception as e:
log_exception(e)

mockio.assert_match_uncolor('ERROR fail: '
mockio.assert_match_uncolor('ERROR fail, '
'cause=RuntimeError '
'traceback=(.+)/test_catch.py:98"?$')
18 changes: 9 additions & 9 deletions tests/sublog/test_context_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ def test_context_logger():
# log level
mockio.assert_match(' DEBUG ')
# message with context
mockio.assert_match(' got request: request_id=3735936685$')
mockio.assert_match(' got request, request_id=3735936685$')

mockio.assert_match_uncolor('INFO logged in: request_id=3735936685 user=igrek page="sweet home"$')
mockio.assert_match_uncolor('INFO logged in, request_id=3735936685 user=igrek page="sweet home"$')
mockio.assert_match_uncolor('WARN im a root$')
mockio.assert_match_uncolor('DEBUG logged out: request_id=3735936685$')
mockio.assert_match_uncolor('DEBUG logged out, request_id=3735936685$')
mockio.assert_match_uncolor('DEBUG 42$')


Expand All @@ -43,13 +43,13 @@ def test_root_context_logger():

logger.debug('exited')

mockio.assert_match_uncolor(' outside context: a=4$')
mockio.assert_match_uncolor(' got request: request_id=3735936685$')
mockio.assert_match_uncolor(' logged in: request_id=3735936685 user=igrek page=home$')
mockio.assert_match_uncolor(' im a root: request_id=3735936685 user=igrek$')
mockio.assert_match_uncolor(' outside context, a=4$')
mockio.assert_match_uncolor(' got request, request_id=3735936685$')
mockio.assert_match_uncolor(' logged in, request_id=3735936685 user=igrek page=home$')
mockio.assert_match_uncolor(' im a root, request_id=3735936685 user=igrek$')
mockio.assert_match_uncolor(
' I\'m a pickle: cause=RuntimeError traceback=.+:40$')
mockio.assert_match_uncolor(' logged out: request_id=3735936685$')
' I\'m a pickle, cause=RuntimeError traceback=.+:40$')
mockio.assert_match_uncolor(' logged out, request_id=3735936685$')
mockio.assert_match_uncolor(' exited$')


Expand Down
10 changes: 5 additions & 5 deletions tests/sublog/test_wrap_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ def test_sublog_wrapping():
logger.warn('attention')
logger.debug('trace')

mockio.assert_match_uncolor('ERROR initializing: liftoff: dupa: '
mockio.assert_match_uncolor('ERROR initializing: liftoff: dupa, '
'request_id=42 speed=zero '
'cause=RuntimeError traceback=(.*)/test_wrap_error.py:10$')
mockio.assert_match_uncolor('ERROR dupa2: a=5 z=fifteen '
mockio.assert_match_uncolor('ERROR dupa2, a=5 z=fifteen '
'cause=ContextError traceback=(.*)/test_wrap_error.py:13$')
mockio.assert_match_uncolor('ERROR dupa3: '
mockio.assert_match_uncolor('ERROR dupa3, '
'cause=RuntimeError traceback=(.*)/test_wrap_error.py:16$')
mockio.assert_match_uncolor('INFO success: param=with_param$')
mockio.assert_match_uncolor('INFO success, param=with_param$')
mockio.assert_match_uncolor('WARN attention$')
mockio.assert_match_uncolor('DEBUG trace$')

Expand All @@ -41,7 +41,7 @@ def test_sublog_wrapping_try_string():
raise RuntimeError('parent') from e
except Exception as e:
assert str(e) == 'initializing: liftoff: parent: dupa'
assert exception_details(e).startswith('initializing: liftoff: parent: dupa: cause=ValueError, traceback='), exception_details(e)
assert exception_details(e).startswith('initializing: liftoff: parent: dupa, cause=ValueError, traceback='), exception_details(e)


try:
Expand Down

0 comments on commit 33c54b7

Please sign in to comment.