Change levelname format in logRecord

Question:

I wonder how I can change the format of levelname in logRecoed using python’s logging package.

formatter = logging.Formatter('%(levelname)-8s %(message)s')

Basically, I want to replace any log name to the first letter of the name. For example,

INFO -> I, 
WARNING -> W, 
ERROR -> E, 

etc.

Asked By: Amir

||

Answers:

You can use the precision field to set a maximum field width:

formatter = logging.Formatter('%(levelname).1s %(message)s')

.1 sets the field width to at most one character, truncating the level to the first character:

>>> for level in ('CRITICAL', 'ERROR', 'INFO', 'WARNING', 'DEBUG'):
...     print '%(level)-.1s %(message)s' % {'level': level, 'message': 'Hello world!'}
... 
C Hello world!
E Hello world!
I Hello world!
W Hello world!
D Hello world!

See the String Formatting Operations documentation:

Conversion: 's'
Meaning: String (converts any Python object using str()).
Notes: (6)

  1. […] The precision determines the maximal number of characters used.
Answered By: Martijn Pieters

If you want completely different levelname then use logging.addLevelName

logging.addLevelName(logging.DEBUG, 'DETAILED')
logging.addLevelName(logging.INFO, 'GENERAL')
Answered By: drt

Adding this on as I wasn’t able to find any clear mention of it, if you prefer brace style formatting, you can accomplish the same thing that @Martijn Pieters with :.1s within your braces. Example:

formatter = Formatter("[{levelname:.1}] {message}")
...
logger.info("hello world!")
[I] hello world!
Answered By: Mattwmaster58
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.