Giter Site home page Giter Site logo

python-colorlog's Introduction

๐Ÿ‘‹ Hi! I build small Python and Rust libraries and command line tools.

python-colorlog's People

Contributors

bachp avatar borntyping avatar buhtz avatar e4r7hbug avatar fabaff avatar fobdy avatar fordhurley avatar francescelies avatar gopackgo90 avatar hackebrot avatar hugovk avatar jdevera avatar jwodder avatar kilianmichiels avatar kmichiels avatar kragniz avatar luislew avatar mdevaev avatar mdraw avatar mgorny avatar nicoddemus avatar northbadge avatar proximous avatar sbraz avatar scop avatar shurane avatar the-compiler avatar veleek avatar voetsjoeba avatar zyxue 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

python-colorlog's Issues

Tests fail with newer versions of pytest

I am currently trying to update the colorlog package for Gentoo Linux to v3.1.4. One of the devs ran into the issue that the tests didn't pass, whereas they passed on my machine. It looks like the version of pytest is responsible. I could reproduce test errors with pytest-3.6.3 and pytest-3.4.2, but tests ran successfully with pytest-3.2.2.

Please see gentoo/gentoo#9653 (comment) for log outputs and reference.

pytest-3.2.2 will be dropped from the Gentoo package tree sooner or later. Is it possible to fix this issue?

interact more nicely with termcolor

Flask's werkzeug add color-codes in its messages using termcolor-package,
ending with a reset-code. This is undoing your own colorlogging until end of line

image

secondary_log_color pydoc is incorrect

in short, doc states it is log_color_{key} but code does {key}_log_color.

At colorlog.py line 76, we have

 The ``secondary_log_colors`` argument can be used to create additional
        ``log_color`` attributes. Each key in the dictionary will set
        ``log_color_{key}``, using the value to select from a different
        ``log_colors`` set.

but the code (colorlog.py line 124) is doing:

setattr(record, name + '_log_color', color)

Add all parameters to basicConfig

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()

colorlog[windows]

when attempting to install colorlog[windows], I get the following warning:
colorlog 3.1.2 does not provide the extra 'windows'
And attempting to run anything that uses colorlog exits with the message:
pkg_resources.UnknownExtra: colorlog 3.1.2 has no such extra feature 'windows'

TTYColoredFormatter should drop every escape sequences, not only colors

Hello,
currently using TTYColoredFormatter will only remove colors from the output, but if you definer your format with other codes (like reset for example) than those sequences are still printed, producing a terrible output if you are redirecting to a file (f.e.)

could you make sure TTYColoredFormatter actually removes every escape sequence? thanks!

Document `thin_` qualifier

I was trying to get gray output and was digging around to add another ansii code but it seems thin_white does the trick.

I'm sure others would like to know about this ๐Ÿ‘

Inconsistent application of color on Windows

I'm attempting to use colorlog on Windows and I'm trying to get colored output to work both inside of PyCharm and inside of powershell.

The following code outputs colored logs when running in Powershell, and no colors when running in PyCharm:

import logging
import colorlog

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
logger.handlers[0].setFormatter(colorlog.ColoredFormatter("%(log_color)s[%(levelname)s] %(message)s%(reset)s"))
logger.debug('Debug')
logger.info('Info')
logger.warning('Warning')
logger.error('Error')

The following code outputs raw color escape codes in Powershell, and color in PyCharm.

import logging

logging.basicConfig(level=logging.DEBUG)
import colorlog

logger = logging.getLogger()
logger.handlers[0].setFormatter(colorlog.ColoredFormatter("%(log_color)s[%(levelname)s] %(message)s%(reset)s"))
logger.debug('Debug')
logger.info('Info')
logger.warning('Warning')
logger.error('Error')

So there's something subtle happening in the initialization that causes the first case to break. The fact that I've already imported colorlog before running logging.basicConfig causes the stream to get wrapped somehow which causes them to get stripped from PyCharm and because the PyCharm console is kind of acting like a Unix console, it ignores the windows commands and renders no color.

In the second case, the color escape codes aren't being removed at all. So I think it's probably only the second case that needs to be fixed. If you've already run logging.basicConfig before importing colorlog, there's nothing you can do to get it to properly wrap the streams. I've tried manually re-initializing colorama among other things, but I'm not positive what the issue is.

Feature: Custom level

Hi,

If already supported, could you please detail how to set a custom logging level with an associated color and formatting? Otherwise that would be a nice addition!

Thanks

Level names are too long

Hi,

Thanks for this awesome library! I've just got it all working with my code base and am delighted. I'm sure it's going to improve my quality of life a lot as I continue working with it!

My least liked aspect of colorlog is the way that CRITICAL and WARNING tend to stick out a lot more than DEBUG or INFO. There's a lot of wasted space there.

Perhaps use shortened names. I would suggest adopting a simple 4-character system:

  • DBG
  • INFO
  • WARN
  • ERR
  • CRIT

This at least is clear enough for me.

Let log_colors None result in defaults

It would be nice if passing log_colors=None resulted in the defaults. You can use the standard pattern:

if log_colors is None:
    log_colors = defaults

It is slightly less convenient otherwise to switch back and forth between user-defined values and the defaults.

colorlog.LevelFormatter does not allow to use dict for fmt parameter on python 3.8

Traceback (most recent call last):
File "D:/gitrep/DevOpsCI/DiasoftBuild/DiasoftBuild.py", line 36, in
from LogInit import file_formatter
File "D:\gitrep\DevOpsCI\DiasoftBuild\CommonLib\LogInit.py", line 98, in
formatter = LevelFormatter(
File "C:\Users\panov-ea\AppData\Roaming\Python\Python38\site-packages\colorlog\colorlog.py", line 160, in init
super(LevelFormatter, self).init(
File "C:\Users\panov-ea\AppData\Roaming\Python\Python38\site-packages\colorlog\colorlog.py", line 91, in init
super(ColoredFormatter, self).init(fmt, datefmt, style)
File "C:\Users\panov-ea\AppData\Local\Programs\Python\Python38-32\lib\logging_init_.py", line 576, in init
self.style.validate()
File "C:\Users\panov-ea\AppData\Local\Programs\Python\Python38-32\lib\logging_init
.py", line 456, in validate
for _, fieldname, spec, conversion in _str_formatter.parse(self._fmt):
File "C:\Users\panov-ea\AppData\Local\Programs\Python\Python38-32\lib\string.py", line 261, in parse
return _string.formatter_parser(format_string)
TypeError: expected str, got dict

Error with reset color and style "{" on Python 3.6

Python 3.6.0a4 64-bit on Windows

The following code produces an error with Python 3.6 but not Python 3.5:

import logging, colorlog

logger  = logging.getLogger()
handler = logging.StreamHandler()

handler.setFormatter(colorlog.ColoredFormatter(
    '{log_color}{levelname}:{reset} {message}', style = '{'))

logging.getLogger().addHandler(handler)

logger.error('TEST')
--- Logging error ---
Traceback (most recent call last):
  File "F:\PortableApps\Python3x\lib\logging\__init__.py", line 985, in emit
    msg = self.format(record)
  File "F:\PortableApps\Python3x\lib\logging\__init__.py", line 831, in format
    return fmt.format(record)
  File "F:\PortableApps\Python3x\lib\site-packages\colorlog\colorlog.py", line 129, in format
    message = super(ColoredFormatter, self).format(record)
  File "F:\PortableApps\Python3x\lib\logging\__init__.py", line 571, in format
    s = self.formatMessage(record)
  File "F:\PortableApps\Python3x\lib\logging\__init__.py", line 540, in formatMessage
    return self._style.format(record)
  File "F:\PortableApps\Python3x\lib\logging\__init__.py", line 392, in format
    return self._fmt.format(**record.__dict__)
KeyError: 'reset'
Call stack:
  File "test.py", line 11, in <module>
    logger.error('TEST')
Message: 'TEST'
Arguments: ()

Purpose of colorlog.getLogger()/StreamHandler()

Your example in the readme also uses colorlog.getLogger() and colorlog.StreamHandler() besides colorlog.ColoredFormatter(). I would expect that only a specialized Formatter is necessary for colorization. And indeed, modifying the example such that only ColoredFormatter() with standard getLogger()/StreamHandler() is used, works as well. Why does colorlog also provide those methods?

Behavior changes based on presense of colorama

Without colorama installed, the provided ColoredFormatter will always use colors, even when redirected to a file (ie. $ ./command.py 2> error_out.txt)

When colorama is installed, colorama detects a non-tty, and strips the colors.

Since colorlog provides a TTYColoredFormater that will strip colors for a non-tty, the above behavior seems not only inconsistent, but unintended. (ie. the user chooses stripping for non-tty by choosing TTYColoredFormater instead of ColoredFormatter, not by having or not having colorama installed.)

I therefore suggest that the colorama init should be called as:
colorama.init(strip=False)
or minimally some other option should be available to colorlog users to 'force' colors or prevent stripping.

I like my logs to have color even when redirected to files. Using 'less -R' let's you still benefit from the colors when reviewing the output.

Color continuation in syslog

Consider the following snippet that simply creates a logger with a colourful formatter and logs a few messages:

import sys
import logging
import logging.handlers
import colorlog


# create the logger with the appropriate name
logger = logging.getLogger(name="somelogger")
# set logger's log-level
logger.setLevel("DEBUG")

# assemble the logging format
fmt = 'someproject: %(process)d %(processName)s %(asctime)-15s %(levelname)-8s %(name)-10s %(message)s'

# create a colourful formatter
formatter_w_color = colorlog.ColoredFormatter(
    fmt="%(log_color)s" + fmt + %(reset)s,
    datefmt="%Y-%m-%dT%H:%M:%SZ",
    reset=True,
    log_colors={
        'DEBUG': 'blue',
        'INFO': 'green',
        'WARNING': 'yellow',
        'ERROR': 'red',
        'CRITICAL': 'red,bg_white',
    },
    secondary_log_colors={},
    style='%'
)

handler_stdout = logging.StreamHandler(sys.stdout)
handler_stdout.setFormatter(formatter_w_color)
logger.addHandler(handler_stdout)

handler_syslog = logging.handlers.SysLogHandler(address="/dev/log")
handler_syslog.setFormatter(formatter_w_color)
logger.addHandler(handler_syslog)


logger.debug("debug")
logger.info("debug")
logger.warning("debug")
logger.error("debug")
logger.critical("debug")

The stdout and syslog can also be seen in the following image:

image

As you can see it all looks good in stdout but in syslog there's a #033[0m that causes the colour to bleed into the next line until the next colour kicks in.

Am I doing sth inordinately stupid or is this to be expected from a syslog handler?

Deprecated README

README contains example of colorlog usage with color_levels argument. The correct name of argument is log_colors.

Add ability to define log_colors and secondary_log_colors in INI file

This might be possible and I'm missing it. It would be great if we could define these in a logging INI config file with something akin to:

[formatter_color]
class=colorlog.ColoredFormatter
format=%(log_color)s%(levelname)-8s%(reset)s [%(name)s]%(reset)s %(message)s%(reset)s
datefmt=%m-%d %H:%M:%S
log_colors=
    DEBUG='cyan'
    INFO='green',
    WARNING='yellow',
    ERROR='red',
    CRITICAL='red,bg_white'

Wrong basic sample in Readme ?

Hi, this a nice useful package.

To integrate it, i naively used the basic sample from Readme: https://github.com/borntyping/python-colorlog#usage

So i coded something like that:

root_logger = colorlog.getLogger("boussole")
root_logger.setLevel(level)
root_logger.setFormatter(colorlog.ColoredFormatter(
    '%(log_color)s%(levelname)s:%(name)s:%(message)s'))
root_logger.addHandler(logging.StreamHandler())

And this resulted in exception complaining about "Logger" that didn't have the setFormatter because this is only a method available from a handler.

Stopping to be so naive, i simply reformatted my code to set formatter from my handler and it works well:

    root_logger = logging.getLogger("boussole")
    root_logger.setLevel(level)
    handler = logging.StreamHandler()
    handler.setFormatter(
        colorlog.ColoredFormatter(
            '%(asctime)s - %(log_color)s%(message)s',
            datefmt="%H:%M:%S"
        )
    )

    root_logger.addHandler(handler)

Did i miss something or maybe your sample is not very accurate ?

AttributeError: 'ColoredFormatter' object has no attribute 'find'

Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/init.py", line 859, in emit
msg = self.format(record)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/init.py", line 732, in format
return fmt.format(record)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/init.py", line 472, in format
if self.usesTime():
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/init.py", line 456, in usesTime
return self._fmt.find("%(asctime)") >= 0
AttributeError: 'ColoredFormatter' object has no attribute 'find'

[Feature request] Logbook support

1. Request

It would be nice, if you add logbook support โ€” a popular alternative default logging module.

2. Justification

I don't find Python modules, that support logbook. If I use modules for custom colored output as pyfancy or colorama, I can highlight messages, but not CRITICAL, ERROR, WARNING, NOTICE, INFO and DEBUG words, example:

NOTICE

It would be nice, if would be possible to highlight all logbook output.

Thanks.

256 color support

256 color support would be awesome, but the current approach used by the library (adding the escape codes to the record) is unlikely to work well with 256+ escape codes. A more elegant solution might be to pass a modified dictionary as the record, overriding __missing__ to return escape codes for keys that are not in the record and would be a valid color.

Embedded IPython shell hangs on ctrl-D if colorlog has been imported

Windows 10.0.15063 Pro
Python 2.7.14
IPython 5.6.0
colorlog 3.1.2

Normal behavior

  1. Execute this code:
import IPython

IPython.embed()
  1. Press ctrl-D
    : Do you really want to exit ([y]/n)?
  2. Press Enter
    : shell exits

Reproduce

  1. Execute this code:
import IPython
import colorlog

IPython.embed()
  1. Press ctrl-D
    : Terminal hangs
    : Windows popup: "python2.exe has stopped working"

Level names are too long

Hi,

Thanks for this awesome library! I've just got it all working with my code base and am delighted. I'm sure it's going to improve my quality of life a lot as I continue working with it!

My least liked aspect of colorlog is the way that CRITICAL and WARNING tend to stick out a lot more than DEBUG or INFO. There's a lot of wasted space there.

Perhaps use shortened names. I would suggest adopting a simple 4-character system:

  • DBG
  • INFO
  • WARN
  • ERR
  • CRIT

I would prefer this system of codes anyway. What do you think?

Switch to deactivate color output

There should be a switch to deactivate the color output. Most of the time for debug purpose.

I use my code on Linux (bash) and Windwos10 (Thonny Pythton GUI). The latter is not able to handle the color codes and output all the escape characters. This is ugly.

I just want to deactivate the color-escape sequences but not the other settings (e.g. format).

Simpler color syntax

It seems this is the simplest for color output:

import colorlog, logging
q = logging.StreamHandler()
q.setFormatter(colorlog.ColoredFormatter(
   "%(log_color)s%(levelname)s%(reset)s %(message)s",
   log_colors = {'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red'}
))
z = logging.getLogger()
z.addHandler(q)
z.warning('abcde')

https://github.com/borntyping/python-colorlog/blob/master/doc/example.py

other projects have simpler syntax:

from logzero import logger
logger.warning('abcde')

colorlog shouldn't call colorama.init() implicitely

Since the contributions by @nicoddemus colorlog calls colorama.init() automatically when being imported.

I think this is wrong. Importing a module shouldn't mangle my sys.stderr/sys.stdout in any way without asking me to (and with no way to prevent it, other than calling colorama.deinit() by hand after importing).

If an user wants to use colorama, they should do this explicitely, not by importing colorlog.

For me, this broke code testing if sys.stderr is None because it then was a colorama-wrapped None, which was totally unexpected.

If you really insist on integrating colorama with colorlog, at least there should be a colorlog.init(). Explicit is better than implicit.

Colorlog 3.0.0: cannot use both foreground and background colors

Hello,

Since the latest release (commit 6041103), using both foreground and background colors in ColorFormatter seems not working anymore.

formatter = ColoredFormatter(
	"%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s",
	datefmt=None,
	reset=True,
	log_colors={
		'DEBUG':    'cyan',
		'INFO':     'green',
		'WARNING':  'yellow',
		'ERROR':    'red',
		'CRITICAL': 'red,bg_white',
	},
	secondary_log_colors={},
	style='%'
)

In this example (same as the README), critical logging log without colors (same as reset).
Before (2.10.0)
after
After (3.0.0)
before

Is it an expected behaviour?

Moreover, the parse_colors method has been removed but the README is not up to date.

Thanks for taking the time to answer me.
Regards,

Tests in test_logging.py fail

When I run py.test, all three tests in test_logging.py fail with the following errors:

=================================== FAILURES ===================================
_____________________________ test_logging_module ______________________________

test_logger = <function test_logger.<locals>.function at 0x7ffff180ed08>

    def test_logging_module(test_logger):
>       test_logger(logging)

colorlog/tests/test_logging.py:9: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
colorlog/tests/conftest.py:36: in function
    assert_log_message(logger.debug, 'a debug message', capsys),
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

log_function = <function debug at 0x7ffff2d92840>, message = 'a debug message'
capsys = <_pytest.capture.CaptureFixture object at 0x7ffff2a67550>

    def assert_log_message(log_function, message, capsys):
        """Call a log function and check the message has been output."""
        log_function(message)
        out, err = capsys.readouterr()
        # Print the output so that py.test shows it when a test fails
        print(err, end='', file=sys.stderr)
        # Assert the message send to the logger was output
>       assert message in err, 'Log message not output to STDERR'
E       AssertionError: Log message not output to STDERR
E       assert 'a debug message' in ''

colorlog/tests/conftest.py:22: AssertionError
------------------------------ Captured log call -------------------------------
conftest.py                 17 DEBUG    a debug message
_____________________________ test_colorlog_module _____________________________

test_logger = <function test_logger.<locals>.function at 0x7ffff180ed90>

    def test_colorlog_module(test_logger):
>       test_logger(colorlog)

colorlog/tests/test_logging.py:13: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
colorlog/tests/conftest.py:36: in function
    assert_log_message(logger.debug, 'a debug message', capsys),
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

log_function = <function debug at 0x7ffff2abc400>, message = 'a debug message'
capsys = <_pytest.capture.CaptureFixture object at 0x7ffff2a67be0>

    def assert_log_message(log_function, message, capsys):
        """Call a log function and check the message has been output."""
        log_function(message)
        out, err = capsys.readouterr()
        # Print the output so that py.test shows it when a test fails
        print(err, end='', file=sys.stderr)
        # Assert the message send to the logger was output
>       assert message in err, 'Log message not output to STDERR'
E       AssertionError: Log message not output to STDERR
E       assert 'a debug message' in ''

colorlog/tests/conftest.py:22: AssertionError
------------------------------ Captured log call -------------------------------
logging.py                  33 DEBUG    a debug message
__________________________ test_colorlog_basicConfig ___________________________

test_logger = <function test_logger.<locals>.function at 0x7ffff180ef28>

    def test_colorlog_basicConfig(test_logger):
        colorlog.basicConfig()
>       test_logger(colorlog.getLogger())

colorlog/tests/test_logging.py:18: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
colorlog/tests/conftest.py:36: in function
    assert_log_message(logger.debug, 'a debug message', capsys),
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

log_function = <bound method Logger.debug of <RootLogger root (WARNING)>>
message = 'a debug message'
capsys = <_pytest.capture.CaptureFixture object at 0x7ffff17d2550>

    def assert_log_message(log_function, message, capsys):
        """Call a log function and check the message has been output."""
        log_function(message)
        out, err = capsys.readouterr()
        # Print the output so that py.test shows it when a test fails
        print(err, end='', file=sys.stderr)
        # Assert the message send to the logger was output
>       assert message in err, 'Log message not output to STDERR'
E       AssertionError: Log message not output to STDERR
E       assert 'a debug message' in ''

colorlog/tests/conftest.py:22: AssertionError
------------------------------ Captured log call -------------------------------
DEBUG:root:a debug message
===================== 3 failed, 24 passed in 0.19 seconds ======================

TTYColoredFormatter throwing a KeyError in newer versions of colorlog

Upgrading colorlog from 2.10.0 to 4.0.2 results in the following error:

/lib/python3.6/site-packages/colorlog/colorlog.py", line 200, in init
self.stream = kwargs.pop('stream')
KeyError: 'stream'

which originates from call to the constructor of TTYColoredFormatter

colorlog.TTYColoredFormatter(fmt='%(green)s[%(asctime)s]%(reset)s %(log_color)s%(message)s', datefmt="%H:%M:%S", log_colors={'DEBUG': 'cyan', 'INFO': 'bold', 'WARNING': 'yellow', 'ERROR': 'bold_red', 'CRITICAL': 'red,bg_white'})

When redirecting stdout, prompt is colored with log level color

Given this minimal example (logtest.py - see below), the prompt is colored in red on Windows (cmd.exe):
grafik

import colorlog
logger  = colorlog.getLogger()
handler = colorlog.StreamHandler()
handler.setFormatter(colorlog.ColoredFormatter(
    '%(log_color)s%(message)s%(reset)s'))
logger.addHandler(handler)
logger.error('test')

Usage example doesn't work

I didn't find the following usage example shown on the README.md page working

import colorlog

logger = colorlog.getLogger('example')
logger.setFormatter(colorlog.ColoredFormatter(
    '%(log_color)s%(levelname)s:%(name)s:%(message)s'))

It prints the following error

Traceback (most recent call last):
  File "lele.py", line 4, in <module>
    logger.setFormatter(colorlog.ColoredFormatter(
AttributeError: 'Logger' object has no attribute 'setFormatter'

This works for me:

import logging
import colorlog

logger = colorlog.getLogger()
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
handler.setFormatter(
    colorlog.ColoredFormatter('%(log_color)s%(levelname)s:%(name)s:%(message)s'))
logger.addHandler(handler)

# Basic setup ENDS here, below are just sample code for printing out some
# example messages of different levels.

logger.debug('some debug message')
logger.info('some info message')
logger.warning('some warning message')
logger.error('some error message')
logger.critical('some critical message')

# Also try a exception message
class ExampleException(Exception):
    pass

try:
    raise ExampleException('This is just an example exception')
except ExampleException as err:
    logger.exception(err)

I have put it together on my blog post, as well: http://zyxue.github.io/2015/08/05/quick-setup-for-python-logging.html

Support force color

My use case is that, I have a service (written in Python and used colorlog) managed by systemd. By default, all logs go to journald, and colorlog detects that stdout is not TTY, so it strip all color codes. But I want to retain these color code, so that I can still see color later (via journalctl).

Foreground colors don't work

When I try to add a foreground color (e.g. "fg_blue"), I always get an error message:

--- Logging error ---
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/logging/__init__.py", line 971, in emit
    msg = self.format(record)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/logging/__init__.py", line 821, in format
    return fmt.format(record)
  File "/Users/Matt3o12/.virtualenvs/myVenvin/lib/python3.4/site-packages/colorlog/colorlog.py", line 67, in format
    message = super(ColoredFormatter, self).format(record)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/logging/__init__.py", line 561, in format
    s = self.formatMessage(record)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/logging/__init__.py", line 530, in formatMessage
    return self._style.format(record)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/logging/__init__.py", line 374, in format
    return self._fmt % record.__dict__
KeyError: 'fg_blue'
Call stack:
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/runpy.py", line 170, in _run_module_as_main
    "__main__", mod_spec)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "my_module", line 4, in <module>
    start()
  File "my_module", line 240, in start
    logger.critical("Critical message")
Message: 'Critical message'
Arguments: ()

Am I missing something or did I configure it wrongly? I'm using Mac OS X and I have colorama installed (although it won't make a difference).

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.