Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: truncated logging level names (string formatting) customization

I am using pythons logging module, and I would like to have a simple change to my logging message. Here is what the formatter looks like, and the result:

console_err_format = logging.Formatter(
    str("%(asctime)s - " + "%(levelname)s" +" - %(message)s"),
    "%H:%M:%S")

12:35:33 - INFO - Assessing reads and library type
12:35:33 - DEBUG - Checking reads...
12:35:33 - WARNING - Error while checking reads...

I would like just the first character of the logger level to be shown:

12:35:33 - I - Assessing reads and library type
12:35:33 - D - Checking reads...
12:35:33 - W - Error while checking reads...

Does anyone know how to do this? I have tried the following things, to no avail:

# attempt 1
console_err_format = logging.Formatter(
    str("%(asctime)s - " +"{0}".format("%(levelname)s"[:1]) +" - %(message)s"), "%H:%M:%S")
# attempt 2
console_err_format = logging.Formatter(
    str("%(asctime)s - " +"%(levelname)s"[:1] +" - %(message)s"), "%H:%M:%S")

Any tips would be appreciated! Bonus points if anyone has figured out howto integrate one of the color logging modules!

like image 884
NWaters Avatar asked Dec 24 '22 12:12

NWaters


2 Answers

Use the format specifier for 1-character precision, as in the following example:

>>> import logging
>>> logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname).1s %(message)s')
>>> logging.debug('Message should be as required')
2017-11-01 00:47:31,409 D Message should be as required
>>> logging.warning('Warning message should be as required')
2017-11-01 00:47:50,702 W Warning message should be as required
>>> 

Note the .1 in front of the s in the %(levelname) specifier, which restricts the output for that value to one (the first) character.

like image 149
Vinay Sajip Avatar answered Jan 26 '23 00:01

Vinay Sajip


I'm not sure how to do it with a formatter, but you can replace the built in level name strings with your own. For example:

logging.addLevelName(logging.WARNING, 'W')

replaces the string associated with the WARNING level with the single character 'W'. Repeating the above for all levels will have the desired effect.

like image 38
Luke Smith Avatar answered Jan 26 '23 01:01

Luke Smith