Logging is an essential part of any mid-large size application which will give you an idea of the inner working of your code. Once you get beyond a small application, just using print statements can be quite cumbersome and difficult to maintain.
The python logging
library is already very useful to allow you to create output of logs, but then they can be quite difficult to read. It can be especially difficult when you are trying to trace through an execution to debug what happened.
This is where the colorlogs
library can really help. With the library you can add some color based on types of logging messages - e.g. red for error, blue for debug etc.
See the following code snippet:
import coloredlogs, logging
mylogs = logging.getLogger(__name__)
coloredlogs.install(level=logging.DEBUG, logger=logger)
# Some examples.
mylogs.debug("This is debug")
mylogs.info("This is info")
mylogs.warning("This is warning")
mylogs.error("This is an error")
mylogs.critical("This is a critical message")
coloredlogs
creates a stream handler and attaches it to the logger passed. It has its own default format and colour settings which can be customised as per interest. Lets first look at the few important parameters we can pass in coloredlogs.install()
-
level
- An integer to denote the level. (Remember logging.DEBUG returns an integer) -
logger
- Name of the logger in which this stream handler has to be attached. (Performs same act aslogger.add_handler()
) -
fmt
- A string denoting the format style. -
datefmt
- A string denoting the format of asctime . -
level_styles
- A dictionary containing the data of level and their colors -
field_styles
- A dictionary containing the data of field and their colors
To find out more about setting up logs, you can see our full article Logging in Python 3, How To Output Logs to File and Console . We give tips on how to setup log output both to a screen and a file, as well as other great tips.
Top comments (0)