Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add all parameters to basicConfig #79

Closed
KilianMichiels opened this issue Dec 23, 2019 · 7 comments
Closed

Add all parameters to basicConfig #79

KilianMichiels opened this issue Dec 23, 2019 · 7 comments

Comments

@KilianMichiels
Copy link
Contributor

Awesome package, very nicely done!

I was wondering why the basicConfig only has the fmt and datefmt option instead of all the ColoredFormatter options since you directly use this class?

I have added them like this and it seems to work fine. Perhaps I'm missing something in how to use the package but this way I can simply use the basicConfig without creating any new handlers etc. and still choose my own colors 👍

def basicConfig(**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=kwargs.get('style', '%'),
                log_colors=kwargs.get('log_colors', None),
                reset=kwargs.get('reset', True),
                secondary_log_colors=kwargs.get('secondary_log_colors', None)))
    finally:
        logging._releaseLock()
@borntyping
Copy link
Owner

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.

@KilianMichiels
Copy link
Contributor Author

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.

@borntyping
Copy link
Owner

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)

@KilianMichiels
Copy link
Contributor Author

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?

@borntyping
Copy link
Owner

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?

@KilianMichiels
Copy link
Contributor Author

KilianMichiels commented Dec 24, 2019

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.

@borntyping
Copy link
Owner

Released in 4.4.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants