Skip to content

Commit e8d09cd

Browse files
committed
Add centralized logger.
1 parent 0ff34f2 commit e8d09cd

File tree

15 files changed

+91
-28
lines changed

15 files changed

+91
-28
lines changed

datajoint/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
"key_hash",
5353
]
5454

55+
from .logging import logger
5556
from .version import __version__
5657
from .settings import config
5758
from .connection import conn, Connection

datajoint/autopopulate.py

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

1313
# noinspection PyExceptionInherit,PyCallingNonCallable
1414

15-
logger = logging.getLogger(__name__)
15+
logger = logging.getLogger(__name__.split(".")[0])
1616

1717

1818
# --- helper functions for multiprocessing --

datajoint/connection.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from .hash import uuid_from_buffer
1818
from .plugin import connection_plugins
1919

20-
logger = logging.getLogger(__name__)
20+
logger = logging.getLogger(__name__.split(".")[0])
2121
query_log_max_length = 300
2222

2323

@@ -339,7 +339,7 @@ def query(
339339
except errors.LostConnectionError:
340340
if not reconnect:
341341
raise
342-
warnings.warn("MySQL server has gone away. Reconnecting to the server.")
342+
logger.warning("MySQL server has gone away. Reconnecting to the server.")
343343
connect_host_hook(self)
344344
if self._in_transaction:
345345
self.cancel_transaction()

datajoint/declare.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ def match_type(attribute_type):
7575
)
7676

7777

78-
logger = logging.getLogger(__name__)
78+
logger = logging.getLogger(__name__.split(".")[0])
7979

8080

8181
def build_foreign_key_parser_old():
@@ -207,7 +207,7 @@ def compile_foreign_key(
207207
)
208208

209209
if obsolete:
210-
warnings.warn(
210+
logger.warning(
211211
'Line "{line}" uses obsolete syntax that will no longer be supported in datajoint 0.14. '
212212
"For details, see issue #780 https://github.com/datajoint/datajoint-python/issues/780".format(
213213
line=line

datajoint/diagram.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@
22
import re
33
import functools
44
import io
5-
import warnings
5+
import logging
66
import inspect
77
from .table import Table
88
from .dependencies import unite_master_parts
99

10+
logger = logging.getLogger(__name__.split(".")[0])
11+
1012
try:
1113
from matplotlib import pyplot as plt
1214

@@ -63,7 +65,7 @@ class Diagram:
6365
"""
6466

6567
def __init__(self, *args, **kwargs):
66-
warnings.warn(
68+
logger.warning(
6769
"Please install matplotlib and pygraphviz libraries to enable the Diagram feature."
6870
)
6971

datajoint/expression.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
)
1818
from .declare import CONSTANT_LITERALS
1919

20-
logger = logging.getLogger(__name__)
20+
logger = logging.getLogger(__name__.split(".")[0])
2121

2222

2323
class QueryExpression:

datajoint/fetch.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from functools import partial
22
from pathlib import Path
3-
import warnings
3+
import logging
44
import pandas
55
import itertools
66
import re
@@ -12,6 +12,8 @@
1212
from .settings import config
1313
from .utils import safe_write
1414

15+
logger = logging.getLogger(__name__.split(".")[0])
16+
1517

1618
class key:
1719
"""
@@ -209,7 +211,7 @@ def __call__(
209211
)
210212

211213
if limit is None and offset is not None:
212-
warnings.warn(
214+
logger.warning(
213215
"Offset set, but no limit. Setting limit to a large number. "
214216
"Consider setting a limit explicitly."
215217
)

datajoint/heading.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from .attribute_adapter import get_adapter, AttributeAdapter
1515

1616

17-
logger = logging.getLogger(__name__)
17+
logger = logging.getLogger(__name__.split(".")[0])
1818

1919
default_attribute_properties = (
2020
dict( # these default values are set in computed attributes

datajoint/logging.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import logging
2+
import os
3+
import sys
4+
import io
5+
6+
logger = logging.getLogger(__name__.split(".")[0])
7+
8+
log_level = os.environ.get("DJ_LOG_LEVEL", "warning").upper()
9+
10+
log_format = logging.Formatter(
11+
"[%(asctime)s][%(funcName)s][%(levelname)s]: %(message)s"
12+
)
13+
14+
stream_handler = logging.StreamHandler() # default handler
15+
stream_handler.setFormatter(log_format)
16+
17+
logger.setLevel(level=log_level)
18+
logger.handlers = [stream_handler]
19+
20+
21+
def excepthook(exc_type, exc_value, exc_traceback):
22+
if issubclass(exc_type, KeyboardInterrupt):
23+
sys.__excepthook__(exc_type, exc_value, exc_traceback)
24+
return
25+
26+
if logger.getEffectiveLevel() == 10:
27+
logger.debug(
28+
"Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback)
29+
)
30+
else:
31+
logger.error(f"Uncaught exception: {exc_value}")
32+
33+
34+
sys.excepthook = excepthook
35+
36+
37+
# https://github.com/tqdm/tqdm/issues/313#issuecomment-267959111
38+
class TqdmToLogger(io.StringIO):
39+
"""
40+
Output stream for TQDM which will output to logger module instead of
41+
the StdOut.
42+
"""
43+
44+
logger = None
45+
level = None
46+
buf = ""
47+
48+
def __init__(self, logger, level=None):
49+
super(TqdmToLogger, self).__init__()
50+
self.logger = logger
51+
self.level = level or logging.INFO
52+
53+
def write(self, buf):
54+
self.buf = buf.strip("\r\n\t ")
55+
56+
def flush(self):
57+
self.logger.log(self.level, self.buf)

datajoint/plugin.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
from pathlib import Path
44
from cryptography.exceptions import InvalidSignature
55
from otumat import hash_pkg, verify
6+
import logging
7+
8+
logger = logging.getLogger(__name__.split(".")[0])
69

710

811
def _update_error_stack(plugin_name):
@@ -15,10 +18,10 @@ def _update_error_stack(plugin_name):
1518
signature = plugin_meta.get_metadata("{}.sig".format(plugin_name))
1619
pubkey_path = str(Path(base_meta.egg_info, "{}.pub".format(base_name)))
1720
verify(pubkey_path=pubkey_path, data=data, signature=signature)
18-
print("DataJoint verified plugin `{}` detected.".format(plugin_name))
21+
logger.info("DataJoint verified plugin `{}` detected.".format(plugin_name))
1922
return True
2023
except (FileNotFoundError, InvalidSignature):
21-
print("Unverified plugin `{}` detected.".format(plugin_name))
24+
logger.warning("Unverified plugin `{}` detected.".format(plugin_name))
2225
return False
2326

2427

0 commit comments

Comments
 (0)