Coverage for pds_crawler/custom_logging.py: 51%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# -*- coding: utf-8 -*-
2# pds-crawler - ETL to index PDS data to pdssp
3# Copyright (C) 2023 - CNES (Jean-Christophe Malapert for Pôle Surfaces Planétaires)
4# This file is part of pds-crawler <https://github.com/pdssp/pds_crawler>
5# SPDX-License-Identifier: LGPL-3.0-or-later
6"""Module for customizing ths logs."""
7import logging
10class LogRecord(logging.LogRecord): # pylint: disable=R0903
11 """Specific class to handle output in logs."""
13 def getMessage(self) -> str:
14 """Returns the message.
16 Format the message according to the type of the message.
18 Returns:
19 str: Returns the message
20 """
21 msg = self.msg
22 if self.args:
23 if isinstance(self.args, dict):
24 msg = msg.format(**self.args)
25 else:
26 msg = msg.format(*self.args)
27 return msg
30class CustomColorFormatter(logging.Formatter):
31 """Color formatter."""
33 # Reset
34 color_Off = "\033[0m" # Text Reset
36 log_colors = {
37 logging.DEBUG: "\033[1;34m", # blue
38 logging.INFO: "\033[0;32m", # green
39 logging.WARNING: "\033[1;33m", # yellow
40 logging.ERROR: "\033[1;31m", # red
41 logging.CRITICAL: "\033[1;41m", # red reverted
42 }
44 def format(self, record) -> str:
45 """Format the log.
47 Args:
48 record: the log record
50 Returns:
51 str: the formatted log record
52 """
53 record.levelname = "{}{}{}".format(
54 CustomColorFormatter.log_colors[record.levelno],
55 record.levelname,
56 CustomColorFormatter.color_Off,
57 )
58 record.msg = "{}{}{}".format(
59 CustomColorFormatter.log_colors[record.levelno],
60 record.msg,
61 CustomColorFormatter.color_Off,
62 )
64 # Select the formatter according to the log if several handlers are
65 # attached to the logger
66 my_formatter = logging.Formatter
67 my_handler = None
68 handlers = logging.getLogger(__name__).handlers
69 for handler in handlers:
70 handler_level = handler.level
71 if (
72 handler_level
73 == logging.getLogger(__name__).getEffectiveLevel()
74 ):
75 if handler.formatter:
76 my_formatter._fmt = ( # pylint: disable=W0212
77 handler.formatter._fmt # pylint: disable=W0212
78 )
79 my_handler = handler
80 break
81 if my_handler is not None:
82 for handler in handlers:
83 if handler != my_handler:
84 logging.getLogger(__name__).removeHandler(handler)
85 return my_formatter.format(self, record) # type: ignore
88class ShellColorFormatter(CustomColorFormatter):
89 """Shell Color formatter."""
91 def format(self, record) -> str:
92 """Format the log.
94 Args:
95 record: the log record
97 Returns:
98 str: the formatted log record
99 """
100 record.msg = "{}{}{}".format(
101 CustomColorFormatter.log_colors[logging.INFO],
102 record.msg,
103 CustomColorFormatter.color_Off,
104 )
105 return record.msg