How to use the colorlog.TTYColoredFormatter function in colorlog

To help you get started, we’ve selected a few colorlog examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github expressvpn / expressvpn_leak_testing / xv_leak_tools / log.py View on Github external
def _configure_logger(logger_name, stream_format, file_format, logfile, level, log_colors):
        logger = logging.getLogger(logger_name)
        logger.setLevel(level)

        # Clear any existing handlers
        logger.handlers = []

        if file_format and logfile:
            file_handler = logging.FileHandler(logfile, mode='a', encoding='utf-8')
            file_handler.setFormatter(logging.Formatter(file_format))
            logger.addHandler(file_handler)

        if stream_format:
            formatter = colorlog.TTYColoredFormatter(stream=sys.stdout, fmt=stream_format, log_colors=log_colors)
            stream_handler = logging.StreamHandler(stream=sys.stdout)
            stream_handler.setFormatter(formatter)
            logger.addHandler(stream_handler)
github koldinger / Tardis / src / Tardis / Daemon.py View on Github external
levels = [logging.WARNING, logging.INFO, logging.DEBUG, logging.TRACE]

    logging.addLevelName(logging.TRACE, 'Message')
    logging.addLevelName(logging.MSGS,  'MSG')

    logging.raiseExceptions = False

    if args.logcfg:
        logging.config.fileConfig(args.logcfg)
        logger = logging.getLogger('')
    else:
        logger = logging.getLogger('')
        if args.logfile or args.daemon:
            logFormat = logging.Formatter("%(asctime)s %(levelname)s : %(message)s")
        else:
            logFormat = colorlog.TTYColoredFormatter("%(asctime)s %(log_color)s%(levelname)s%(reset)s : %(message)s", stream=sys.stdout)

        verbosity = args.verbose

        if args.local:
            # Always send output to stderr for local connections
            handler = logging.StreamHandler()
        elif args.logfile:
            handler = logging.handlers.WatchedFileHandler(args.logfile)
        elif args.daemon:
            handler = logging.handlers.SysLogHandler()
        else:
            handler = logging.StreamHandler()

        handler.setFormatter(logFormat)
        logger.addHandler(handler)
github fossasia / susi_linux / main / __main__.py View on Github external
def get_colorlog_handler(short=False):
    # Short log format is for use under systemd.
    # Here we exclude some info, because they will be added by journalctl.
    if short:
        log_format = '%(log_color)s%(levelname)s:%(reset)s %(message)s'
    else:
        log_format = '%(log_color)s%(asctime)s %(levelname)s:%(name)s:%(reset)s %(message)s'
    handler = colorlog.StreamHandler()
    handler.setFormatter(
        colorlog.TTYColoredFormatter(
            log_format,
            stream=sys.stderr,
            datefmt='%Y-%m-%d %H:%M:%S'))
    return handler
github apache / airflow / airflow / utils / log / colored_log.py View on Github external
from colorlog import TTYColoredFormatter
from termcolor import colored

ARGS = {"attrs": ["bold"]}

DEFAULT_COLORS = {
    "DEBUG": "red",
    "INFO": "",
    "WARNING": "yellow",
    "ERROR": "red",
    "CRITICAL": "red",
}


class CustomTTYColoredFormatter(TTYColoredFormatter):
    """
    Custom log formatter which extends `colored.TTYColoredFormatter`
    by adding attributes to message arguments and coloring error
    traceback.
    """
    def __init__(self, *args, **kwargs):
        kwargs["stream"] = sys.stdout or kwargs.get("stream")
        kwargs["log_colors"] = DEFAULT_COLORS
        super().__init__(*args, **kwargs)

    @staticmethod
    def _color_arg(arg: Any) -> Union[str, float, int]:
        if isinstance(arg, (int, float)):
            # In case of %d or %f formatting
            return arg
        return colored(str(arg), **ARGS)  # type: ignore
github koldinger / Tardis / src / Tardis / Util.py View on Github external
def setupLogging(verbosity=1, levels=None, format=None, stream=sys.stdout):
    if levels is None:
        levels = [logging.WARNING, logging.INFO, logging.DEBUG]

    loglevel = levels[verbosity] if verbosity < len(levels) else logging.DEBUG

    if format is None:
        if loglevel <= logging.DEBUG:
            format = "%(log_color)s%(levelname)s%(reset)s : %(filename)s:%(lineno)d: %(message)s"
        else:
            format = "%(log_color)s%(levelname)s%(reset)s : %(message)s"

    colors = colorlog.default_log_colors.copy()
    colors.update({ 'DEBUG': 'green' })

    formatter = colorlog.TTYColoredFormatter(format, log_colors=colors, stream=stream)
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    logging.root.addHandler(handler)

    logging.raiseExceptions = False

    logger = logging.getLogger("")
    logger.setLevel(loglevel)
    return logger