Giter VIP home page Giter VIP logo

rainbow_logging_handler's Introduction

rainbow_logging_handler

https://travis-ci.org/laysakura/rainbow_logging_handler.png?branch=master Latest PyPI version

Ultimate Python colorized logger.

http://github.com/laysakura/rainbow_logging_handler/raw/master/doc/screenshot.png

This script runs like above screenshot.

import sys
import logging
from rainbow_logging_handler import RainbowLoggingHandler

def main_func():
    # setup `logging` module
    logger = logging.getLogger('test_logging')
    logger.setLevel(logging.DEBUG)
    formatter = logging.Formatter("[%(asctime)s] %(name)s %(funcName)s():%(lineno)d\t%(message)s")  # same as default

    # setup `RainbowLoggingHandler`
    handler = RainbowLoggingHandler(sys.stderr, color_funcName=('black', 'yellow', True))
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    logger.debug("debug msg")
    logger.info("info msg")
    logger.warn("warn msg")
    logger.error("error msg")
    logger.critical("critical msg")

    try:
        raise RuntimeError("Opa!")
    except Exception as e:
        logger.exception(e)

if __name__ == '__main__':
    main_func()

http://github.com/miohtama/rainbow_logging_handler/raw/master/doc/screenshot_django.png

Django is a popular Python web framework.

Put the following to your settings.py to get more pleasant development server console output:

# Add this to your settings.py
if DEBUG:
    # Install rainbow logging handler when running Django in develoment mode
    import sys
    LOGGING["handlers"]["rainbow"] = {"level": "DEBUG", "class": "rainbow_logging_handler.RainbowLoggingHandler", 'stream': sys.stderr}
    LOGGING["loggers"]['']["handlers"].append("rainbow")

More about configuring loggers for Django.

Set handler_console section in develop.ini:

[handler_console]
class = rainbow_logging_handler.RainbowLoggingHandler
args = (sys.stderr,)
level = NOTSET
format = [%(asctime)s] %(name)s %(funcName)s():%(lineno)d\t%(message)s

As apparent from above screenshot, each column of logs are differently colored. Even default coloring should make log reading easier.

Every column colors are customizable.

formatter = logging.Formatter('%(pathname)s [%(module)s] - %(funcName)s:L%(lineno)d : %(message)s')
handler   = RainbowLoggingHandler(
    sys.stderr,
    # Customizing each column's color
    color_pathname=('black', 'red'  , True), color_module=('yellow', None, False),
    color_funcName=('blue' , 'white', True), color_lineno=('green' , None, False),
)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.info("hello custom world")

Above code produces output like this.

http://github.com/laysakura/rainbow_logging_handler/raw/master/doc/screenshot-custom-color.png

Linux, BSD, Mac OS, and Windows are supposed to be supported.

Runs with both Python 2.6 or higher & Python 3.2 or higher.

pip install rainbow_logging_handler
pip install -e "git+https://github.com/laysakura/rainbow_logging_handler.git#egg=rainbow_logging_handler"

Mikko Ohtamaa <[email protected]>, Sho Nakatani <[email protected]>

And special thanks to 10sr for advice.

This is free and unencumbered public domain software. For more information, see <http://unlicense.org/> or the accompanying LICENSE.txt file.

rainbow_logging_handler's People

Contributors

delfick avatar eirenik0 avatar laysakura avatar miohtama avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

rainbow_logging_handler's Issues

Logging when python interpreter exits fails when it cannot import sys

The first statement of RainbowLoggingHandler._emit() is: import sys statement.
Importing libraries when python shutsdown raises the following exception:

--- Logging error ---
Traceback (most recent call last):
  File "/python/lib/site_packages/rainbow_logging_handler/__init__.py", line 194, in emit
    msg = self._encode(msg)
  File "/python/lib/site_packages/rainbow_logging_handler/__init__.py", line 210, in _encode
    import sys
ImportError: sys.meta_path is None, Python is likely shutting down
Call stack:
  File "/python/app/foo.py", line 65, in __del__
    self.close()
  File "/python/lib/logging/__init__.py", line 1294, in debug
    self._log(DEBUG, msg, args, **kwargs)
  File "/python/lib/logging/__init__.py", line 1442, in _log
    self.handle(record)
  File "/python/lib/logging/__init__.py", line 1452, in handle
    self.callHandlers(record)
  File "/python/lib/logging/__init__.py", line 1514, in callHandlers
    hdlr.handle(record)
  File "/python/lib/logging/__init__.py", line 863, in handle
    self.emit(record)
  File "/python/lib/site_packages/rainbow_logging_handler/__init__.py", line 200, in emit
    self.handleError(record)
Message: 'Closing somethid: %s'
Arguments: ('something')

Many libraries use logging statements just before python interpreter exits, e.g inside finalizers, and this causes an annoying cascade of log-failures at the exit of the application.

The solution is to move the import sys statement at the top of the rainbow_logging_handler/__init__.py file.

Merge into logutils

Hi,

Originally I tried to reach logutils author and ask if we can integrate RainbowLogger in that package, so that a separate package would not be needed.

But somehow I either missed the reply or never got the reply back.

If you feel lucky you could try to reach logutils author again.

logutils still imported

Hi,

I am not sure if I understood your comment correctly (separate).

logutils is still imported and used in init.py. Was your plan to get rid of this dependency?

Can't install 2.2.1

Hello,

┌─(stephen.moore@iambob-iLaptop, 29 Jul)────────────(~)────┐
└─(19:31)$ virtualenv tester
New python executable in tester/bin/python
Installing setuptools, pip...done.

┌─(stephen.moore@iambob-iLaptop, 29 Jul)────────────(~)────┐
└─(19:32)$ pip install rainbow_logging_handler==2.2.1
Downloading/unpacking rainbow-logging-handler==2.2.1
Downloading rainbow_logging_handler-2.2.1.zip
Running setup.py (path:/private/var/folders/k_/s20d12h56ln9xgzrbj22h5rc9b481m/T/pip_build_stephen.moore/rainbow-logging-handler/setup.py) egg_info for pa#
    Traceback (most recent call last):
    File "<string>", line 17, in <module>
    File "/private/var/folders/k_/s20d12h56ln9xgzrbj22h5rc9b481m/T/pip_build_stephen.moore/rainbow-logging-handler/setup.py", line 9, in <module>
        long_description = open('README.rst').read(),
    IOError: [Errno 2] No such file or directory: 'README.rst'
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):

File "<string>", line 17, in <module>

File "/private/var/folders/k_/s20d12h56ln9xgzrbj22h5rc9b481m/T/pip_build_stephen.moore/rainbow-logging-handler/setup.py", line 9, in <module>

    long_description = open('README.rst').read(),

IOError: [Errno 2] No such file or directory: 'README.rst'

----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1 in /private/var/folders/k_/s20d12h56ln9xgzrbj22h5rc9b481m/T/pip_build_stephen.moore/rainbow-log#
Storing debug log for failure in /Users/stephen.moore/.pip/pip.log

How can I change the asctime format?

The default date_format is HH:MM:SS. I need what is the default logger date_format, i.e. %Y-%m-%d %H:%M:%S with milliseconds as .%(msecs)03d.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.