Installation
you can install the following library simply by just running:
pip install logging-colorizer
Usage
In addition to use this library first we need to import it using:
from logging_colorizer import Log
after that we instantiate our logger and we also can costumize its format
log = Log()
log = Log(format="%(light_black)s TIME: %(asctime)s %(cyan)s|%(light_black)s IP: %(clientip)s %(cyan)s|%(light_black)s CODE: %(Code)s %(cyan)s|%(purple)s [%(lvl)s] %(cyan)s|%(log_color)s %(message)s %(reset)s")
The levels to trigger a log
Info | info | inf | i |
warning | warning | warn | w |
debug | debug | dbg | d |
error | error | err | e |
critical | critical | crit | c |
So all of three lines bellow do the exact same thing
log.info('Here is the info')
log.inf('Here is the info')
log.i('Here is the info')
And so on...
The colors
For using different colors in your logger you should provide the color on the format argument of the module like this:
log = Log(format="%(purple)s %(message)s %(reset)s")
in the above example in every call of the logger, it writes the message in purple color and then resets the color for future logs.(just incase if there were no colors provided)
instead of purple, you can use these colors:
- light_black, black, bold_black
- light_red, red, bold_red
- light_green, green, bold_green
- light_yellow, yellow, bold_yellow
- light_blue, blue, bold_blue
- light_purple, purple, bold_purple
- light_cyan, cyan, bold_cyan
- light_white, white, bold_white
Example
A boilerplate code can be like this:
from logging_colorizer import Log
import requests
def check_ip():
session = requests.session()
ip = session.get("http://icanhazip.com").text.replace("\n","")
session.close()
return ip
ip = check_ip()
log = Log(format="%(light_black)s TIME: %(asctime)s %(cyan)s|%(light_black)s IP: %(clientip)s %(cyan)s|%(light_black)s CODE: %(Code)s %(cyan)s|%(purple)s [%(lvl)s] %(cyan)s|%(log_color)s %(message)s %(reset)s")
log.info('Here is an info log', extra_plus_ali={'clientip': ip, "Code": "Boilerplate.py"})
log.warning('Here is a warning log', extra_plus_ali={'clientip': ip, "Code": "Boilerplate.py"})
log.debug('Here is a debug log', extra_plus_ali={'clientip': ip, "Code": "Boilerplate.py"})
log.error('Here is an error log', extra_plus_ali={'clientip': ip, "Code": "Boilerplate.py"})
log.critical('Here is a critical log', extra_plus_ali={'clientip': ip, "Code": "Boilerplate.py"})
- Which is supposed to write the current time, ip, the code name in black color and the log level in purple and the message color is based on the log level.
- if the log level is info, the message color will be green
- if the log level is warning, the message color will be yellow
- if the log level is debug, the message color will be white
- if the log level is error, the message color will be red
- if the log level is critical, the message color will be bold red
Which returns an output like bellow:
