12

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!

2 Answers 2

20

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.

Sign up to request clarification or add additional context in comments.

Comments

8

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.

2 Comments

This works great (and is easy to add coloring too, but the way!). If no-one else responds with a way to manipulate the formatter itself, I'd say this is the the best bet
This is a great addition to setting the formatting. E.g. it's possible to truncate the level to 3 chars via formatter and have the levels named DBG, WRN or FTL which are much easier to read in my opinion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.