Skip to content

Commit

Permalink
Minor tweaks to the calibre log wrap
Browse files Browse the repository at this point in the history
  • Loading branch information
ping committed Sep 13, 2023
1 parent cbb55fa commit 4b0add8
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 10 deletions.
24 changes: 14 additions & 10 deletions calibre-plugin/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,17 @@ class CalibreLogHandler(logging.Handler):
"""

def __init__(self, logger):
self.calibre_log = None
if not logger:
super().__init__()
self.log = None
return

if isinstance(logger, CalibreLogHandler):
self.log = logger.log
# just in case we accidentally pass in a wrapped log
self.calibre_log = logger.calibre_log
else:
self.log = logger
calibre_log_level = self.log.filter_level
self.calibre_log = logger
calibre_log_level = self.calibre_log.filter_level
level = logging.NOTSET
if calibre_log_level <= DEBUG:
level = logging.DEBUG
Expand All @@ -72,20 +74,22 @@ def __init__(self, logger):
super().__init__(level)

def emit(self, record):
if not self.log:
if not self.calibre_log:
return
msg = self.format(record)
if record.levelno <= logging.DEBUG:
self.log.debug(msg)
self.calibre_log.debug(msg)
elif record.levelno == logging.INFO:
self.log.info(msg)
self.calibre_log.info(msg)
elif record.levelno == logging.WARNING:
self.log.warning(msg)
self.calibre_log.warning(msg)
elif record.levelno >= logging.ERROR:
self.log.error(msg)
self.calibre_log.error(msg)
else:
self.calibre_log.info(msg)


def create_job_logger(log):
def create_job_logger(log) -> logging.Logger:
"""
Convert calibre's logger into a more standardised logger
Expand Down
17 changes: 17 additions & 0 deletions tests/calibre.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
import sys
import unittest

Expand Down Expand Up @@ -66,6 +67,22 @@ def test_truncate_for_display(self):
),
)

def test_log_handler(self):
from calibre.utils.logging import Log, DEBUG
from calibre_plugins.overdrive_libby.utils import create_job_logger

logger: logging.Logger = create_job_logger(Log(DEBUG))
msg = "Level %s"
logger.debug(msg, logging.DEBUG)
logger.info(msg, logging.INFO)
logger.warning(msg, logging.WARNING)
logger.error(msg, logging.ERROR)
logger.critical(msg, logging.CRITICAL)
try:
1 / 0
except: # noqa
logger.exception("Test Exception")


# Run with:
# calibre-customize -b calibre-plugin && calibre-debug -e tests/calibre.py
Expand Down

0 comments on commit 4b0add8

Please sign in to comment.