Python logging.BASIC_FORMAT Examples

The following are 16 code examples for showing how to use logging.BASIC_FORMAT(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module logging , or try the search function .

Example 1
Project: modelforge   Author: src-d   File: slogging.py    License: Apache License 2.0 6 votes vote down vote up
def formatMessage(self, record: logging.LogRecord) -> str:
        """Convert the already filled log record to a string."""
        level_color = "0"
        text_color = "0"
        fmt = ""
        if record.levelno <= logging.DEBUG:
            fmt = "\033[0;37m" + logging.BASIC_FORMAT + "\033[0m"
        elif record.levelno <= logging.INFO:
            level_color = "1;36"
            lmsg = record.message.lower()
            if self.GREEN_RE.search(lmsg):
                text_color = "1;32"
        elif record.levelno <= logging.WARNING:
            level_color = "1;33"
        elif record.levelno <= logging.CRITICAL:
            level_color = "1;31"
        if not fmt:
            fmt = "\033[" + level_color + \
                  "m%(levelname)s\033[0m:%(rthread)s:%(name)s:\033[" + text_color + \
                  "m%(message)s\033[0m"
        fmt = _fest + fmt
        record.rthread = reduce_thread_id(record.thread)
        return fmt % record.__dict__ 
Example 2
Project: Safejumper-for-Desktop   Author: proxysh   File: test_stdlib.py    License: GNU General Public License v2.0 6 votes vote down vote up
def handlerAndBytesIO():
    """
    Construct a 2-tuple of C{(StreamHandler, BytesIO)} for testing interaction
    with the 'logging' module.

    @return: handler and io object
    @rtype: tuple of L{StreamHandler} and L{io.BytesIO}
    """
    output = BytesIO()
    stream = output
    template = py_logging.BASIC_FORMAT
    if _PY3:
        stream = TextIOWrapper(output, encoding="utf-8", newline="\n")
    formatter = py_logging.Formatter(template)
    handler = py_logging.StreamHandler(stream)
    handler.setFormatter(formatter)
    return handler, output 
Example 3
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_no_kwargs(self):
        logging.basicConfig()

        # handler defaults to a StreamHandler to sys.stderr
        self.assertEqual(len(logging.root.handlers), 1)
        handler = logging.root.handlers[0]
        self.assertIsInstance(handler, logging.StreamHandler)
        self.assertEqual(handler.stream, sys.stderr)

        formatter = handler.formatter
        # format defaults to logging.BASIC_FORMAT
        self.assertEqual(formatter._style._fmt, logging.BASIC_FORMAT)
        # datefmt defaults to None
        self.assertIsNone(formatter.datefmt)
        # style defaults to %
        self.assertIsInstance(formatter._style, logging.PercentStyle)

        # level is not explicitly set
        self.assertEqual(logging.root.level, self.original_logging_level) 
Example 4
Project: learn_python3_spider   Author: wistbean   File: test_stdlib.py    License: MIT License 6 votes vote down vote up
def handlerAndBytesIO():
    """
    Construct a 2-tuple of C{(StreamHandler, BytesIO)} for testing interaction
    with the 'logging' module.

    @return: handler and io object
    @rtype: tuple of L{StreamHandler} and L{io.BytesIO}
    """
    output = BytesIO()
    stream = output
    template = py_logging.BASIC_FORMAT
    if _PY3:
        stream = TextIOWrapper(output, encoding="utf-8", newline="\n")
    formatter = py_logging.Formatter(template)
    handler = py_logging.StreamHandler(stream)
    handler.setFormatter(formatter)
    return handler, output 
Example 5
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 6 votes vote down vote up
def test_no_kwargs(self):
        logging.basicConfig()

        # handler defaults to a StreamHandler to sys.stderr
        self.assertEqual(len(logging.root.handlers), 1)
        handler = logging.root.handlers[0]
        self.assertIsInstance(handler, logging.StreamHandler)
        self.assertEqual(handler.stream, sys.stderr)

        formatter = handler.formatter
        # format defaults to logging.BASIC_FORMAT
        self.assertEqual(formatter._style._fmt, logging.BASIC_FORMAT)
        # datefmt defaults to None
        self.assertIsNone(formatter.datefmt)
        # style defaults to %
        self.assertIsInstance(formatter._style, logging.PercentStyle)

        # level is not explicitly set
        self.assertEqual(logging.root.level, self.original_logging_level) 
Example 6
def test_no_kwargs(self):
        logging.basicConfig()

        # handler defaults to a StreamHandler to sys.stderr
        self.assertEqual(len(logging.root.handlers), 1)
        handler = logging.root.handlers[0]
        self.assertIsInstance(handler, logging.StreamHandler)
        self.assertEqual(handler.stream, sys.stderr)

        formatter = handler.formatter
        # format defaults to logging.BASIC_FORMAT
        self.assertEqual(formatter._style._fmt, logging.BASIC_FORMAT)
        # datefmt defaults to None
        self.assertIsNone(formatter.datefmt)
        # style defaults to %
        self.assertIsInstance(formatter._style, logging.PercentStyle)

        # level is not explicitly set
        self.assertEqual(logging.root.level, self.original_logging_level) 
Example 7
Project: fragile   Author: FragileTech   File: slogging.py    License: MIT License 5 votes vote down vote up
def formatMessage(self, record: logging.LogRecord) -> str:
        """Convert the already filled log record to a string."""
        level_color = "0"
        text_color = "0"
        fmt = ""
        if record.levelno <= logging.DEBUG:
            fmt = "\033[0;37m" + logging.BASIC_FORMAT + "\033[0m"
        elif record.levelno <= logging.INFO:
            level_color = "1;36"
            lmsg = record.message.lower()
            if self.GREEN_RE.search(lmsg):
                text_color = "1;32"
        elif record.levelno <= logging.WARNING:
            level_color = "1;33"
        elif record.levelno <= logging.CRITICAL:
            level_color = "1;31"
        if not fmt:
            fmt = (
                "\033["
                + level_color
                + "m%(levelname)s\033[0m:%(rthread)s:%(name)s:\033["
                + text_color
                + "m%(message)s\033[0m"
            )
        fmt = _fest + fmt
        record.rthread = reduce_thread_id(record.thread)
        return fmt % record.__dict__ 
Example 8
Project: topology   Author: HPENetworking   File: logging.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self._file_handler = None
        self._file_formatter = kwargs.pop(
            'file_formatter', logging.BASIC_FORMAT
        )
        super(FileLogger, self).__init__(*args, **kwargs) 
Example 9
Project: bacpypes   Author: JoelBender   File: debugging.py    License: MIT License 5 votes vote down vote up
def ModuleLogger(globs):
    """Create a module level logger.

    To debug a module, create a _debug variable in the module, then use the
    ModuleLogger function to create a "module level" logger.  When a handler
    is added to this logger or a child of this logger, the _debug variable will
    be incremented.

    All of the calls within functions or class methods within the module should
    first check to see if _debug is set to prevent calls to formatter objects
    that aren't necessary.
    """
    # make sure that _debug is defined
    if '_debug' not in globs:
        raise RuntimeError("define _debug before creating a module logger")

    # logger name is the module name
    logger_name = globs['__name__']

    # create a logger to be assigned to _log
    logger = logging.getLogger(logger_name)

    # put in a reference to the module globals
    logger.globs = globs

    # if this is a "root" logger add a default handler for warnings and up
    if '.' not in logger_name:
        hdlr = logging.StreamHandler()
        hdlr.setLevel(logging.WARNING)
        hdlr.setFormatter(logging.Formatter(logging.BASIC_FORMAT, None))
        logger.addHandler(hdlr)

    return logger

#
#   Typical Use
#

# some debugging 
Example 10
Project: bacpypes   Author: JoelBender   File: debugging.py    License: MIT License 5 votes vote down vote up
def __init__(self, color=None):
        logging.Formatter.__init__(self, logging.BASIC_FORMAT, None)

        # check the color
        if color is not None:
            if color not in range(8):
                raise ValueError("colors are 0 (black) through 7 (white)")

        # save the color
        self.color = color 
Example 11
Project: bacpypes   Author: JoelBender   File: debugging.py    License: MIT License 5 votes vote down vote up
def ModuleLogger(globs):
    """Create a module level logger.

    To debug a module, create a _debug variable in the module, then use the
    ModuleLogger function to create a "module level" logger.  When a handler
    is added to this logger or a child of this logger, the _debug variable will
    be incremented.

    All of the calls within functions or class methods within the module should
    first check to see if _debug is set to prevent calls to formatter objects
    that aren't necessary.
    """
    # make sure that _debug is defined
    if '_debug' not in globs:
        raise RuntimeError("define _debug before creating a module logger")

    # logger name is the module name
    logger_name = globs['__name__']

    # create a logger to be assigned to _log
    logger = logging.getLogger(logger_name)

    # put in a reference to the module globals
    logger.globs = globs

    # if this is a "root" logger add a default handler for warnings and up
    if '.' not in logger_name:
        hdlr = logging.StreamHandler()
        hdlr.setLevel(logging.WARNING)
        hdlr.setFormatter(logging.Formatter(logging.BASIC_FORMAT, None))
        logger.addHandler(hdlr)

    return logger

#
#   Typical Use
#

# some debugging 
Example 12
Project: bacpypes   Author: JoelBender   File: debugging.py    License: MIT License 5 votes vote down vote up
def __init__(self, color=None):
        logging.Formatter.__init__(self, logging.BASIC_FORMAT, None)

        # check the color
        if color is not None:
            if color not in range(8):
                raise ValueError("colors are 0 (black) through 7 (white)")

        # save the color
        self.color = color 
Example 13
Project: bacpypes   Author: JoelBender   File: debugging.py    License: MIT License 5 votes vote down vote up
def ModuleLogger(globs):
    """Create a module level logger.

    To debug a module, create a _debug variable in the module, then use the
    ModuleLogger function to create a "module level" logger.  When a handler
    is added to this logger or a child of this logger, the _debug variable will
    be incremented.

    All of the calls within functions or class methods within the module should
    first check to see if _debug is set to prevent calls to formatter objects
    that aren't necessary.
    """
    # make sure that _debug is defined
    if not globs.has_key('_debug'):
        raise RuntimeError("define _debug before creating a module logger")

    # logger name is the module name
    logger_name = globs['__name__']

    # create a logger to be assigned to _log
    logger = logging.getLogger(logger_name)

    # put in a reference to the module globals
    logger.globs = globs

    # if this is a "root" logger add a default handler for warnings and up
    if '.' not in logger_name:
        hdlr = logging.StreamHandler()
        hdlr.setLevel(logging.WARNING)
        hdlr.setFormatter(logging.Formatter(logging.BASIC_FORMAT, None))
        logger.addHandler(hdlr)

    return logger

#
#   Typical Use
#

# some debugging 
Example 14
Project: uModbus   Author: AdvancedClimateSystems   File: utils.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def log_to_stream(stream=sys.stderr, level=logging.NOTSET,
                  fmt=logging.BASIC_FORMAT):
    """ Add :class:`logging.StreamHandler` to logger which logs to a stream.

    :param stream. Stream to log to, default STDERR.
    :param level: Log level, default NOTSET.
    :param fmt: String with log format, default is BASIC_FORMAT.
    """
    fmt = Formatter(fmt)
    handler = StreamHandler()
    handler.setFormatter(fmt)
    handler.setLevel(level)

    log.addHandler(handler) 
Example 15
Project: diffxpy   Author: theislab   File: log_cfg.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def enable_logging(verbosity=logging.ERROR, stream=sys.stderr, format=logging.BASIC_FORMAT):
    unconfigure_logging()

    logger.setLevel(verbosity)
    _handler = logging.StreamHandler(stream)
    _handler.setFormatter(logging.Formatter(format, None))
    logger.addHandler(_handler)


# If we are in an interactive environment (like Jupyter), set loglevel to INFO and pipe the output to stdout. 
Example 16
Project: pibooth   Author: pibooth   File: utils.py    License: MIT License 5 votes vote down vote up
def configure_logging(level=logging.INFO, msgfmt=logging.BASIC_FORMAT, datefmt=None, filename=None):
    """Configure root logger for console printing.
    """
    root = logging.getLogger()

    if not root.handlers:
        # Set lower level to be sure that all handlers receive the logs
        root.setLevel(logging.DEBUG)

        if filename:
            # Create a file handler, all levels are logged
            filename = osp.abspath(osp.expanduser(filename))
            dirname = osp.dirname(filename)
            if not osp.isdir(dirname):
                os.makedirs(dirname)
            hdlr = logging.FileHandler(filename)
            hdlr.setFormatter(logging.Formatter(msgfmt, datefmt))
            hdlr.setLevel(logging.DEBUG)
            root.addHandler(hdlr)

        # Create a console handler
        hdlr = BlockConsoleHandler(sys.stdout)
        hdlr.setFormatter(logging.Formatter(msgfmt, datefmt))
        if level is not None:
            hdlr.setLevel(level)
            BlockConsoleHandler.default_level = level
        root.addHandler(hdlr)