Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change levelname format in logRecord

Tags:

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.

like image 315
Amir Avatar asked Dec 12 '14 22:12

Amir


2 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.
like image 172
Martijn Pieters Avatar answered Oct 04 '22 02:10

Martijn Pieters


If you want completely different levelname then use logging.addLevelName

logging.addLevelName(logging.DEBUG, 'DETAILED') logging.addLevelName(logging.INFO, 'GENERAL') 
like image 41
drt Avatar answered Oct 04 '22 02:10

drt