All Projects → borntyping → Python Colorlog

borntyping / Python Colorlog

Licence: mit
A colored formatter for the python logging module

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to Python Colorlog

Plog
Portable, simple and extensible C++ logging library
Stars: ✭ 1,061 (+56.95%)
Mutual labels:  library, logging
Vlog
An in-display logging library for Android 📲
Stars: ✭ 86 (-87.28%)
Mutual labels:  library, logging
Logging Log4j2
Apache Log4j 2 is an upgrade to Log4j that provides significant improvements over its predecessor, Log4j 1.x, and provides many of the improvements available in Logback while fixing some inherent problems in Logback's architecture.
Stars: ✭ 1,133 (+67.6%)
Mutual labels:  library, logging
Litter
Litter is a pretty printer library for Go data structures to aid in debugging and testing.
Stars: ✭ 1,137 (+68.2%)
Mutual labels:  library, logging
Pygogo
A Python logging library with superpowers
Stars: ✭ 265 (-60.8%)
Mutual labels:  library, logging
Belogging
Easy and opinionated logging configuration for Python apps
Stars: ✭ 20 (-97.04%)
Mutual labels:  library, logging
Liblognorm
a fast samples-based log normalization library
Stars: ✭ 81 (-88.02%)
Mutual labels:  library, logging
Humblelogging
HumbleLogging is a lightweight C++ logging framework. It aims to be extendible, easy to understand and as fast as possible.
Stars: ✭ 15 (-97.78%)
Mutual labels:  library, logging
Golib
Go Library [DEPRECATED]
Stars: ✭ 194 (-71.3%)
Mutual labels:  library, logging
Java Markdown Generator
Java library to generate markdown
Stars: ✭ 159 (-76.48%)
Mutual labels:  library, logging
Logsip
A simple, concise, colorful logger for Go
Stars: ✭ 94 (-86.09%)
Mutual labels:  library, logging
Log Process Errors
Show some ❤️ to Node.js process errors
Stars: ✭ 424 (-37.28%)
Mutual labels:  library, logging
Go Grpc Middleware
Golang gRPC Middlewares: interceptor chaining, auth, logging, retries and more.
Stars: ✭ 4,170 (+516.86%)
Mutual labels:  library, logging
Faster
Fast persistent recoverable log and key-value store + cache, in C# and C++.
Stars: ✭ 4,846 (+616.86%)
Mutual labels:  library, logging
Flint
The Flint framework for building apps on Apple platforms using Feature Driven Development
Stars: ✭ 636 (-5.92%)
Mutual labels:  logging
Lambdacd
a library to define a continuous delivery pipeline in code
Stars: ✭ 655 (-3.11%)
Mutual labels:  library
Nanojs
Minimal standalone JS library for DOM manipulation
Stars: ✭ 636 (-5.92%)
Mutual labels:  library
Httplog
Log outgoing HTTP requests in ruby
Stars: ✭ 633 (-6.36%)
Mutual labels:  logging
Cordova Plugin File
Apache Cordova Plugin file
Stars: ✭ 664 (-1.78%)
Mutual labels:  library
Storyboard
End-to-end, hierarchical, real-time, colorful logs and stories
Stars: ✭ 652 (-3.55%)
Mutual labels:  logging

Log formatting with colors!

colorlog.ColoredFormatter is a formatter for use with Python's logging module that outputs records using terminal colors.

Installation

Install from PyPI with:

pip install colorlog

Several Linux distributions provide official packages (Debian, Gentoo, OpenSuse and Ubuntu), and others have user provided packages (Arch AUR, BSD ports, Conda, Fedora packaging scripts).

Usage

import colorlog

handler = colorlog.StreamHandler()
handler.setFormatter(colorlog.ColoredFormatter(
	'%(log_color)s%(levelname)s:%(name)s:%(message)s'))

logger = colorlog.getLogger('example')
logger.addHandler(handler)

The ColoredFormatter class takes several arguments:

  • format: The format string used to output the message (required).
  • datefmt: An optional date format passed to the base class. See logging.Formatter.
  • reset: Implicitly adds a color reset code to the message output, unless the output already ends with one. Defaults to True.
  • log_colors: A mapping of record level names to color names. The defaults can be found in colorlog.default_log_colors, or the below example.
  • secondary_log_colors: A mapping of names to log_colors style mappings, defining additional colors that can be used in format strings. See below for an example.
  • style: Available on Python 3.2 and above. See logging.Formatter.

Color escape codes can be selected based on the log records level, by adding parameters to the format string:

  • log_color: Return the color associated with the records level.
  • <name>_log_color: Return another color based on the records level if the formatter has secondary colors configured (see secondary_log_colors below).

Multiple escape codes can be used at once by joining them with commas when configuring the color for a log level (but can't be used directly in the format string). For example, black,bg_white would use the escape codes for black text on a white background.

The following escape codes are made available for use in the format string:

  • {color}, fg_{color}, bg_{color}: Foreground and background colors.
  • bold, bold_{color}, fg_bold_{color}, bg_bold_{color}: Bold/bright colors.
  • thin, thin_{color}, fg_thin_{color}: Thin colors (terminal dependent).
  • reset: Clear all formatting (both foreground and background colors).

The available color names are black, red, green, yellow, blue, purple, cyan and white.

Examples

Example output

The following code creates a ColoredFormatter for use in a logging setup, using the default values for each argument.

from colorlog import ColoredFormatter

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='%'
)

Using secondary_log_colors

Secondary log colors are a way to have more than one color that is selected based on the log level. Each key in secondary_log_colors adds an attribute that can be used in format strings (message becomes message_log_color), and has a corresponding value that is identical in format to the log_colors argument.

The following example highlights the level name using the default log colors, and highlights the message in red for error and critical level log messages.

from colorlog import ColoredFormatter

formatter = ColoredFormatter(
	"%(log_color)s%(levelname)-8s%(reset)s %(message_log_color)s%(message)s",
	secondary_log_colors={
		'message': {
			'ERROR':    'red',
			'CRITICAL': 'red'
		}
	}
)

With dictConfig

logging.config.dictConfig({
	'formatters': {
		'colored': {
			'()': 'colorlog.ColoredFormatter',
			'format': "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s"
		}
	}
})

A full example dictionary can be found in tests/test_colorlog.py.

With fileConfig

...

[formatters]
keys=color

[formatter_color]
class=colorlog.ColoredFormatter
format=%(log_color)s%(levelname)-8s%(reset)s %(bg_blue)s[%(name)s]%(reset)s %(message)s from fileConfig
datefmt=%m-%d %H:%M:%S

An instance of ColoredFormatter created with those arguments will then be used by any handlers that are configured to use the color formatter.

A full example configuration can be found in tests/test_config.ini.

With custom log levels

ColoredFormatter will work with custom log levels added with logging.addLevelName:

import logging, colorlog
TRACE = 5
logging.addLevelName(TRACE, 'TRACE')
formatter = colorlog.ColoredFormatter(log_colors={'TRACE': 'yellow'})
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = logging.getLogger('example')
logger.addHandler(handler)
logger.setLevel('TRACE')
logger.log(TRACE, 'a message using a custom level')

Compatibility

colorlog works on Python 2.6 and above, including Python 3.

On Windows, colorama is required for colorlog to work properly. It will automatically be included when installing colorlog on windows.

Tests

Tests similar to the above examples are found in tests/test_colorlog.py.

tox will run the tests under all compatible python versions.

Status

colorlog is in maintainance mode. I try and ensure bugfixes are published, but compatibility with Python 2.6+ and Python 3+ makes this a difficult codebase to add features to. Any changes that might break backwards compatibility for existing users will not be considered.

Alternatives

There are some more modern libraries for improving Python logging you may find useful.

Projects using colorlog

Licence

Copyright (c) 2012-2020 Sam Clements [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].