Skip to content

Commit 65140ba

Browse files
committed
logging_helper: update to latest version
1 parent 1e9f3dd commit 65140ba

File tree

2 files changed

+21
-17
lines changed

2 files changed

+21
-17
lines changed

src/cachew/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def orjson_dumps(*args, **kwargs): # type: ignore[misc]
4848
from .backend.file import FileBackend
4949
from .backend.sqlite import SqliteBackend
5050
from .common import SourceHash
51-
from .logging_helper import makeLogger
51+
from .logging_helper import make_logger
5252
from .marshall.cachew import CachewMarshall, build_schema
5353
from .utils import (
5454
CachewException,
@@ -85,7 +85,7 @@ class settings:
8585

8686

8787
def get_logger() -> logging.Logger:
88-
return makeLogger(__name__)
88+
return make_logger(__name__)
8989

9090

9191
BACKENDS: Dict[Backend, Type[AbstractBackend]] = {

src/cachew/logging_helper.py

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@ def test() -> None:
3131
M("\n Also exception logging is kinda lame, doesn't print traceback by default unless you remember to pass exc_info:")
3232
l.exception(ex) # type: ignore[possibly-undefined] # pylint: disable=used-before-assignment
3333

34-
M("\n\n With makeLogger you get a reasonable logging format, colours (via colorlog library) and other neat things:")
34+
M("\n\n With make_logger you get a reasonable logging format, colours (via colorlog library) and other neat things:")
3535

36-
ll = makeLogger('test') # No need for basicConfig!
36+
ll = make_logger('test') # No need for basicConfig!
3737
ll.info("default level is INFO")
3838
ll.debug("... so this shouldn't be displayed")
3939
ll.warning("warnings are easy to spot!")
@@ -105,6 +105,14 @@ def setup_logger(logger: str | logging.Logger, *, level: LevelIsh = None) -> Non
105105
# if it's already set, the user requested a different logging level, let's respect that
106106
logger.setLevel(lvl)
107107

108+
_setup_handlers_and_formatters(name=logger.name)
109+
110+
111+
# cached since this should only be done once per logger instance
112+
@lru_cache(None)
113+
def _setup_handlers_and_formatters(name: str) -> None:
114+
logger = logging.getLogger(name)
115+
108116
logger.addFilter(AddExceptionTraceback())
109117

110118
ch = logging.StreamHandler()
@@ -128,10 +136,12 @@ def setup_logger(logger: str | logging.Logger, *, level: LevelIsh = None) -> Non
128136
else:
129137
# log_color/reset are specific to colorlog
130138
FORMAT_COLOR = FORMAT.format(start='%(log_color)s', end='%(reset)s')
131-
fmt = FORMAT_COLOR if ch.stream.isatty() else FORMAT_NOCOLOR
132139
# colorlog should detect tty in principle, but doesn't handle everything for some reason
133140
# see https://github.com/borntyping/python-colorlog/issues/71
134-
formatter = colorlog.ColoredFormatter(fmt)
141+
if ch.stream.isatty():
142+
formatter = colorlog.ColoredFormatter(FORMAT_COLOR)
143+
else:
144+
formatter = logging.Formatter(FORMAT_NOCOLOR)
135145

136146
ch.setFormatter(formatter)
137147

@@ -142,16 +152,13 @@ def setup_logger(logger: str | logging.Logger, *, level: LevelIsh = None) -> Non
142152
# todo also amend by post about defensive error handling?
143153
class AddExceptionTraceback(logging.Filter):
144154
def filter(self, record: logging.LogRecord) -> bool:
145-
s = super().filter(record)
146-
if s is False:
147-
return False
148155
if record.levelname == 'ERROR':
149156
exc = record.msg
150157
if isinstance(exc, BaseException):
151158
if record.exc_info is None or record.exc_info == (None, None, None):
152159
exc_info = (type(exc), exc, exc.__traceback__)
153160
record.exc_info = exc_info
154-
return s
161+
return True
155162

156163

157164
# todo also save full log in a file?
@@ -189,8 +196,7 @@ def emit(self, record: logging.LogRecord) -> None:
189196
self.handleError(record)
190197

191198

192-
@lru_cache(None) # cache so it's only initialized once
193-
def makeLogger(name: str, *, level: LevelIsh = None) -> logging.Logger:
199+
def make_logger(name: str, *, level: LevelIsh = None) -> logging.Logger:
194200
logger = logging.getLogger(name)
195201
setup_logger(logger, level=level)
196202
return logger
@@ -201,9 +207,7 @@ def makeLogger(name: str, *, level: LevelIsh = None) -> logging.Logger:
201207
# OK, when stdout is not a tty, enlighten doesn't log anything, good
202208
def get_enlighten():
203209
# TODO could add env variable to disable enlighten for a module?
204-
from unittest.mock import Mock
205-
206-
# Mock to return stub so cients don't have to think about it
210+
from unittest.mock import Mock # Mock to return stub so cients don't have to think about it
207211

208212
# for now hidden behind the flag since it's a little experimental
209213
if os.environ.get('ENLIGHTEN_ENABLE', None) is None:
@@ -230,6 +234,6 @@ def get_enlighten():
230234

231235

232236
## legacy/deprecated methods for backwards compatilibity
233-
LazyLogger = makeLogger
234-
logger = makeLogger
237+
LazyLogger = make_logger
238+
logger = make_logger
235239
##

0 commit comments

Comments
 (0)