xref: /aosp_15_r20/external/google-cloud-java/owl-bot-postprocessor/synthtool/log.py (revision 55e87721aa1bc457b326496a7ca40f3ea1a63287)
1# Copyright 2018 Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import logging
16import sys
17
18try:
19    from colorlog import ColoredFormatter
20except ImportError:
21    ColoredFormatter
22
23SUCCESS = 25
24
25
26class LoggerWithSuccess(logging.getLoggerClass()):  # type: ignore
27    def __init__(self, name, level=logging.NOTSET):
28        super(LoggerWithSuccess, self).__init__(name, level)
29        logging.addLevelName(SUCCESS, "SUCCESS")
30
31    def success(self, msg, *args, **kwargs):
32        if self.isEnabledFor(SUCCESS):
33            self._log(SUCCESS, msg, args, **kwargs)
34        else:  # pragma: no cover
35            pass
36
37
38def _setup_logging(color: bool = bool(ColoredFormatter)):
39    logging.getLogger("urllib3.connectionpool").setLevel(logging.ERROR)
40    logging.setLoggerClass(LoggerWithSuccess)
41
42    # Silence any noisy loggers here.
43    logging.getLogger("watchdog.observers").setLevel(logging.INFO)
44
45
46def configure_logger(name: str, color: bool = bool(ColoredFormatter)):
47    """Create and configure the default logger for autosynth.
48    The logger will prefix the log message with the current time and the
49    log severity.
50    """
51    logger = logging.getLogger(name)
52    logger.setLevel(logging.DEBUG)
53
54    handler = logging.StreamHandler()
55    handler.setLevel(logging.DEBUG)
56
57    if color is True and sys.stdout.isatty():
58        formatter = ColoredFormatter(
59            "%(asctime)s %(purple)s%(name)s > %(log_color)s%(message)s",
60            reset=True,
61            log_colors={
62                "DEBUG": "cyan",
63                "INFO": "blue",
64                "WARNING": "yellow",
65                "ERROR": "red",
66                "CRITICAL": "red,bg_yellow",
67                "SUCCESS": "green",
68            },
69        )
70    else:
71        formatter = logging.Formatter(  # type: ignore
72            "%(asctime)s %(name)s [%(levelname)s] > %(message)s"
73        )
74
75    handler.setFormatter(formatter)
76    logger.addHandler(handler)
77    return logger
78
79
80_setup_logging()
81logger = configure_logger("synthtool")
82
83
84def success(*args, **kwargs):
85    logger.success(*args, **kwargs)
86
87
88def debug(*args, **kwargs):
89    logger.debug(*args, **kwargs)
90
91
92def info(*args, **kwargs):
93    logger.info(*args, **kwargs)
94
95
96def warning(*args, **kwargs):
97    logger.warning(*args, **kwargs)
98
99
100def error(*args, **kwargs):
101    logger.warning(*args, **kwargs)
102
103
104def exception(*args, **kwargs):
105    logger.warning(*args, **kwargs)
106
107
108def critical(*args, **kwargs):
109    logger.critical(*args, **kwargs)
110