Package: coloredlogs
Thecoloredlogspackage enables colored terminal output for Python’sloggingmodule. TheColoredFormatterclass inherits fromlogging.Formatterand usesANSI escape sequencesto render your logging messages in color. It uses only
standard colors so it should work on any UNIX terminal. It’s currently tested
on Python 2.7, 3.5+ and PyPy (2 and 3). On Windowscoloredlogsautomatically
tries to enable native ANSI support (on up-to-date Windows 10 installations)
and falls back on usingcolorama(if installed). Here is a screen shot of the
demo that is printed when the commandcoloredlogs--demois executed:Note that the screenshot above includes custom logging levels defined by myverboselogspackage: if you install bothcoloredlogsandverboselogsit
will Just Work (verboselogsis of course not required to usecoloredlogs).InstallationOptional dependenciesUsageFormat of log messagesEnabling millisecond precisionCustom logging fieldsChanging text styles and colorsColored output from cronModifying your crontabModifying your Python codeContactLicenseInstallationThecoloredlogspackage is available onPyPIwhich means installation should
be as simple as:$pipinstallcoloredlogsThere’s actually a multitude of ways to install Python packages (e.g. theper
user site-packages directory,virtual environmentsor just installing
system wide) and I have no intention of getting into that discussion here, so
if this intimidates you then read up on your options before returning to these
instructions 😉.Optional dependenciesNative ANSI support on Windows requires an up-to-date Windows 10 installation.
If this is not working for you then consider installing thecoloramapackage:$pipinstallcoloramaOncecoloramais installed it will be used automatically.UsageHere’s an example of how easy it is to get started:importcoloredlogs,logging# Create a logger object.logger=logging.getLogger(__name__)# By default the install() function installs a handler on the root logger,# this means that log messages from your code and log messages from the# libraries that you use will all show up on the terminal.coloredlogs.install(level='DEBUG')# If you don't want to see log messages from libraries, you can pass a# specific logger object to the install() function. In this case only log# messages originating from that logger will show up on the terminal.coloredlogs.install(level='DEBUG',logger=logger)# Some examples.logger.debug("this is a debugging message")logger.info("this is an informational message")logger.warning("this is a warning message")logger.error("this is an error message")logger.critical("this is a critical message")Format of log messagesTheColoredFormatterclass supports user defined log formats so you can use
any log format you like. The default log format is as follows:%(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)sThis log format results in the following output:2015-10-23 03:32:22 peter-macbook coloredlogs.demo[30462] DEBUG message with level 'debug'
2015-10-23 03:32:23 peter-macbook coloredlogs.demo[30462] VERBOSE message with level 'verbose'
2015-10-23 03:32:24 peter-macbook coloredlogs.demo[30462] INFO message with level 'info'
...You can customize the log format and styling using environment variables as
well as programmatically, please refer to theonline documentationfor
details.Enabling millisecond precisionIf you’re switching fromlogging.basicConfig()tocoloredlogs.install()you may notice that timestamps no longer include milliseconds. This is because
coloredlogs doesn’t output milliseconds in timestamps unless you explicitly
tell it to. There are three ways to do that:The easy way is to pass themillisecondsargument tocoloredlogs.install():coloredlogs.install(milliseconds=True)This became supported inrelease 7.1(due to#16).Alternatively you can change the log formatto include ‘msecs’:%(asctime)s,%(msecs)03d %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)sHere’s what the call tocoloredlogs.install()would then look like:coloredlogs.install(fmt='%(asctime)s,%(msecs)03d %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s')Customizing the log format also enables you to change the delimiter that
separates seconds from milliseconds (the comma above). This became possible
inrelease 3.0which added support for user defined log formats.If the use of%(msecs)disn’t flexible enough you can instead add%fto the date/time format, it will be replaced by the value of%(msecs)03d.
Support for the%fdirective was added torelease 9.3(due to#45).Custom logging fieldsThe following custom log format fields are supported:%(hostname)sprovides the hostname of the local system.%(programname)sprovides the name of the currently running program.%(username)sprovides the username of the currently logged in user.Whencoloredlogs.install()detects that any of these fields are used in the
format string the applicablelogging.Filtersubclasses are automatically
registered to populate the relevant log record fields.Changing text styles and colorsThe online documentation containsan example of customizing the text styles and
colors.Colored output from cronWhencoloredlogsis used in acronjob, the output that’s e-mailed to you by
cron won’t contain any ANSI escape sequences becausecoloredlogsrealizes
that it’s not attached to an interactive terminal. If you’d like to have colors
e-mailed to you by cron there are two ways to make it happen:Modifying your crontabModifying your Python codeModifying your crontabHere’s an example of a minimal crontab:MAILTO="your-email-address@here"
CONTENT_TYPE="text/html"
* * * * * root coloredlogs --to-html your-commandThecoloredlogsprogram is installed when you install thecoloredlogsPython package. When you executecoloredlogs--to-htmlyour-commandit runsyour-commandunder the external programscript(you need to have this
installed). This makesyour-commandthink that it’s attached to an
interactive terminal which means it will output ANSI escape sequences which
will then be converted to HTML by thecoloredlogsprogram. Yes, this is a
bit convoluted, but it works great :-)Modifying your Python codeTheColoredCronMailerclass provides a context manager that automatically
enables HTML output when the$CONTENT_TYPEvariable has been correctly set
in the crontab.This requires mycapturerpackage which you can install usingpip install 'coloredlogs[cron]'. The[cron]extra will pull incapturer2.4 or newer
which is required to capture the output while silencing it - otherwise you’d
get duplicate output in the emails sent bycron.The context manager can also be used to retroactively silence output that has
already been produced, this can be useful to avoid spammy cron jobs that have
nothing useful to do but still email their output to the system administrator
every few minutes :-).ContactThe latest version ofcoloredlogsis available onPyPIandGitHub. Theonline documentationis available on Read The Docs and includes achangelog. For bug reports please create an issue onGitHub. If you have
questions, suggestions, etc. feel free to send me an e-mail atpeter@peterodding.com.LicenseThis software is licensed under theMIT license.© 2020 Peter Odding.