Commit 17c9383e authored by Arnaud ROUX's avatar Arnaud ROUX

Make logging.py more integrated with django logging.

    - Log level define only by handlers, logger is set as the lowest level
    - Each handler type cannot be duplicate.
parent 5de49770
......@@ -5,25 +5,43 @@ import os
from django.conf import settings
def get_logger(log_name):
def get_logger(log_name, create_console_handler=False) -> logging.Logger:
"""Return logger object which own two handlers at differents log level."""
os.makedirs(settings.LOG_DIR, exist_ok=True)
logfile_handler = logging.handlers.TimedRotatingFileHandler(settings.LOG_DIR + "/" + log_name,
logger = logging.getLogger(log_name)
logfile_handler = logging.handlers.TimedRotatingFileHandler(os.path.join(settings.LOG_DIR, log_name),
when="midnight",
interval=1,
backupCount=30)
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
logfile_handler.setFormatter(formatter)
logfile_handler.suffix = "%Y-%m-%d"
# Critical errors go to stderr, useful for cron commands
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.CRITICAL)
logfile_formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
logfile_handler.setLevel(logging.INFO)
logfile_handler.setFormatter(logfile_formatter)
logfile_handler.suffix = "%Y-%m-%d"
logger = logging.getLogger(log_name)
# logfile_handler is created only if they are no
# handler instance with same type and file target.
rotating_file_handler_exist = any([type(handler) == logging.handlers.TimedRotatingFileHandler
for handler in logger.handlers
if getattr(handler, 'baseFilename', '') == logfile_handler.baseFilename])
if not logger.handlers:
if not rotating_file_handler_exist:
logger.addHandler(logfile_handler)
# Console handler added only if they are no console handlers ever attached to 'logger'
if logging.StreamHandler not in [type(handler) for handler in logger.handlers]:
console_handler = logging.StreamHandler()
console_formatter = logging.Formatter('[%(levelname)s] %(message)s')
console_handler.setFormatter(console_formatter)
console_handler.setLevel(logging.CRITICAL)
if settings.DEBUG:
console_handler.setLevel(logging.DEBUG)
logger.addHandler(console_handler)
# Only handlers define log level, parent logger set at the lowest level
if settings.DEBUG:
logger.setLevel(logging.DEBUG)
else:
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment