Giter Site home page Giter Site logo

Comments (7)

borntyping avatar borntyping commented on August 16, 2024

In theory, because colorlog.basicConfig calls logging.basicConfig which will throw an error on any unfamiliar arguments: https://github.com/python/cpython/blob/3.8/Lib/logging/__init__.py#L1992-L1994

I would expect this to throw an error if any of the formatter keyword arguments are set, but I don't currently have a machine available to reproduce this on.

from python-colorlog.

KilianMichiels avatar KilianMichiels commented on August 16, 2024

I see, weird that I do not get any errors then..But you are right! How about a function call to basicConfig where one could pass on a created ColoredFormatter to still be able to use all the functionality of ColoredFormatter?
basicConfig would then become something like:

def basicConfig(formatter=None, **kwargs):
    """Call ``logging.basicConfig`` and override the formatter it creates."""
    logging.basicConfig(**kwargs)
    logging._acquireLock()
    try:
        if formatter is None:
            formatter = ColoredFormatter(fmt=BASIC_FORMAT, datefmt=None)
        stream = logging.root.handlers[0]
        stream.setFormatter(formatter)
            
    finally:
        logging._releaseLock()

Or if you wish to keep your level of similarity to the logging.basicConfig module, you can also add the ColoredFormatter arguments to the basicConfig function call. This way, these arguments are eaten before the **kwargs are passed on to logging.basicConfig?
Something like this:

def basicConfig(style='%', log_colors=None, reset=True, secondary_log_colors=None, **kwargs):
    """Call ``logging.basicConfig`` and override the formatter it creates."""
    logging.basicConfig(**kwargs)
    logging._acquireLock()
    try:
        stream = logging.root.handlers[0]
        stream.setFormatter(
            ColoredFormatter(
                fmt=kwargs.get('format', BASIC_FORMAT),
                datefmt=kwargs.get('datefmt', None),
                style=style,
                log_colors=log_colors,
                reset=reset,
                secondary_log_colors=secondary_log_colors)))
    finally:
        logging._releaseLock()

Unless there is another way to make sure that the cmd output is colored in the colors that I want, I think this functionality is really missing.. If there is a simple way to have my own colors in the cmd output (and I'm completely missing this), please let me know.

from python-colorlog.

borntyping avatar borntyping commented on August 16, 2024

That change would probably be a good improvement to the library!

At the moment, the only option for customising the formatter is managing setup yourself - there are examples in the README but this is the shorted I can (theoretically) make it:

import colorlog
import logging

handler = colorlog.StreamHandler()
handler.setFormatter(colorlog.ColoredFormatter(...))
logging.basicConfig(handlers=handlers)

from python-colorlog.

KilianMichiels avatar KilianMichiels commented on August 16, 2024

Which change do you mean? The first one or the second one?

I tried it with the colorlog.StreamHandler() but something was probably wrong since I got all the output twice, once formatted with BASIC_FORMAT and once in the way I wanted it.

However, it would be very useful for my code if one of these changes was added to the package, would you like me to create a merge request for this?

from python-colorlog.

borntyping avatar borntyping commented on August 16, 2024

Which change do you mean? The first one or the second one?

The second one - adding the extra parameters to colorlog.basicConfig.

I tried it with the colorlog.StreamHandler() but something was probably wrong since I got all the output twice, once formatted with BASIC_FORMAT and once in the way I wanted it.

That probably shouldn't happen - did you still call basicConfig (either from logging or colorlog) before adding another handler?

from python-colorlog.

KilianMichiels avatar KilianMichiels commented on August 16, 2024

The second one - adding the extra parameters to colorlog.basicConfig.

Ok, perfect! I'll make a pull request then :)

That probably shouldn't happen - did you still call basicConfig (either from logging or colorlog) before adding another handler?

I cannot reproduce the duplicate output with your example: #79 (comment)
However, when I do the following:

import logging
import colorlog

handler = colorlog.StreamHandler()
handler.setFormatter(
    colorlog.ColoredFormatter(
        fmt='%(log_color)s%(asctime)s  %(levelname)-8s %(name)-15s - %(funcName)s - %(message)s',
        datefmt="%Y-%m-%d %H-%M-%S",
        log_colors={
           'DEBUG': 'bold_purple',
           'INFO': 'bold_white',
           'WARNING': 'bold_yellow',
           'ERROR': 'bold_red',
           'CRITICAL': 'bold_red,bg_white',
        }
    )
)
logging.basicConfig(handlers=[handler])
logger = colorlog.getLogger(logger_name)

The output is formatted correctly, but it is still not colored the way I pass it on in the log_colors.. Passing on the exact same parameters to the basicConfig in my previous solution (#79 (comment)) does the trick though, but this is not very clean with the possible errors of course.

from python-colorlog.

borntyping avatar borntyping commented on August 16, 2024

Released in 4.4.0.

from python-colorlog.

Related Issues (20)

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.