Python coloredlogs.ColoredFormatter() Examples

The following are 6 code examples of coloredlogs.ColoredFormatter(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module coloredlogs , or try the search function .
Example #1
Source File: logging.py    From ParlAI with MIT License 6 votes vote down vote up
def _build_formatter(self):
        prefix_format = f'{self.prefix} ' if self.prefix else ''
        if COLORED_LOGS and sys.stdout.isatty():
            return coloredlogs.ColoredFormatter(
                prefix_format + COLORED_FORMAT,
                datefmt=CONSOLE_DATE_FORMAT,
                level_styles=COLORED_LEVEL_STYLES,
                field_styles={},
            )
        elif sys.stdout.isatty():
            return logging.Formatter(
                prefix_format + CONSOLE_FORMAT, datefmt=CONSOLE_DATE_FORMAT,
            )
        else:
            return logging.Formatter(
                prefix_format + LOGFILE_FORMAT, datefmt=LOGFILE_DATE_FORMAT,
            ) 
Example #2
Source File: logger.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def init_logger(log_requests=False):
    """ Initialize the logger """

    logger = logging.getLogger(__name__.split(".")[0])
    for handler in logger.handlers:  # pragma: no cover
        logger.removeHandler(handler)

    if os.name == "nt" and "colorama" in sys.modules:  # pragma: no cover
        colorama.init()

    formatter = coloredlogs.ColoredFormatter(fmt="%(asctime)s: %(message)s")
    handler = logging.StreamHandler(stream=sys.stdout)
    handler.setLevel(logging.DEBUG)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)
    logger.propagate = False

    if log_requests:
        requests.packages.urllib3.add_stderr_logger() 
Example #3
Source File: log.py    From trains with Apache License 2.0 6 votes vote down vote up
def _make_stream_handler(cls, level=None, stream=sys.stdout, colored=False):
        ch = logging.StreamHandler(stream=stream)
        ch.setLevel(level)
        formatter = None

        # if colored, try to import colorama & coloredlogs (by default, not in the requirements)
        if colored:
            try:
                import colorama
                from coloredlogs import ColoredFormatter
                colorama.init()
                formatter = ColoredFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            except ImportError:
                colored = False

        # if we don't need or failed getting colored formatter
        if not colored or not formatter:
            formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        ch.setFormatter(formatter)
        return ch 
Example #4
Source File: logger.py    From MetaCI with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def init_logger(model):
    """ Initialize the logger. """

    logger = logging.getLogger("cumulusci")

    # Remove existing handlers
    for handler in list(logger.handlers):
        handler.stream.flush(force=True)
        logger.removeHandler(handler)

    # Create the custom handler
    formatter = coloredlogs.ColoredFormatter(fmt="%(asctime)s: %(message)s")
    handler = LogHandler(model)
    handler.setLevel(logging.DEBUG)
    handler.setFormatter(formatter)

    logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)
    logger.propagate = False

    return logger 
Example #5
Source File: log.py    From MultiQC with GNU General Public License v3.0 4 votes vote down vote up
def init_log(logger, loglevel=0, no_ansi=False):
    """
    Initializes logging.
    Prints logs to console with level defined by loglevel
    Also prints verbose log to the multiqc data directory if available.
    (multiqc_data/multiqc.log)

    Args:
        loglevel (str): Determines the level of the log output.
    """
    # File for logging
    global log_tmp_dir, log_tmp_fn
    log_tmp_dir = tempfile.mkdtemp()
    log_tmp_fn = os.path.join(log_tmp_dir, 'multiqc.log')

    # Logging templates
    debug_template = '[%(asctime)s] %(name)-50s [%(levelname)-7s]  %(message)s'
    info_template = '[%(levelname)-7s] %(module)15s : %(message)s'

    # Base level setup
    logger.setLevel(getattr(logging, 'DEBUG'))

    # Set up the console logging stream
    console = logging.StreamHandler()
    console.setLevel(getattr(logging, loglevel))
    level_styles = coloredlogs.DEFAULT_LEVEL_STYLES
    level_styles['debug'] = {'faint': True}
    if loglevel == 'DEBUG':
        if no_ansi or not sys.stderr.isatty():
            console.setFormatter(logging.Formatter(debug_template))
        else:
            console.setFormatter(coloredlogs.ColoredFormatter(fmt=debug_template, level_styles=level_styles))
    else:
        if no_ansi or not sys.stderr.isatty():
            console.setFormatter(logging.Formatter(info_template))
        else:
            console.setFormatter(coloredlogs.ColoredFormatter(fmt=info_template, level_styles=level_styles))
    logger.addHandler(console)

    # Now set up the file logging stream if we have a data directory
    file_handler = logging.FileHandler(log_tmp_fn, encoding='utf-8')
    file_handler.setLevel(getattr(logging, 'DEBUG')) # always DEBUG for the file
    file_handler.setFormatter(logging.Formatter(debug_template))
    logger.addHandler(file_handler) 
Example #6
Source File: logging_manager.py    From floris with Apache License 2.0 4 votes vote down vote up
def _setup_logger():
    """
    Configures the root logger based on the default or user-specified settings.
    As needed, a StreamHandler is created for console logging or FileHandler
    is created for file logging. Either or both are attached to the root
    logger for use throughout FLORIS.

    Returns:
        logging.Logger: The root logger from the `logging` module.
    """
    # Configure logging for the root logger
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    # level_styles = {'warning': {'color': 'red', 'bold': False}}
    fmt_console = "%(name)s %(levelname)s %(message)s"
    fmt_file = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

    file_name = "floris_{:%Y-%m-%d-%H_%M_%S}.log".format(datetime.now())

    # TODO: understand why this doesnt work and fix it!
    # if logger.hasHandlers():
    #     print(logger.handlers, len(logger.handlers))
    #     for i, handler in enumerate(logger.handlers):
    #         print(i, handler)
    #         logger.removeHandler(handler)
    #     print(logger.handlers, len(logger.handlers))

    # Remove all existing handlers before adding new ones
    while logger.hasHandlers():
        logger.removeHandler(logger.handlers[0])

    # Configure and add the console handler
    if LOG_TO_CONSOLE:
        console_handler = logging.StreamHandler()
        console_handler.setLevel(CONSOLE_LEVEL)
        console_format = coloredlogs.ColoredFormatter(
            # level_styles=level_styles,
            fmt=fmt_console
        )
        console_handler.setFormatter(console_format)
        console_handler.addFilter(TracebackInfoFilter(clear=True))
        logger.addHandler(console_handler)

    # Configure and add the file handler
    if LOG_TO_FILE:
        file_handler = logging.FileHandler(file_name)
        file_handler.setLevel(FILE_LEVEL)
        file_format = logging.Formatter(fmt_file)
        file_handler.setFormatter(file_format)
        file_handler.addFilter(TracebackInfoFilter(clear=False))
        logger.addHandler(file_handler)

    return logger