Change name format in logRecord

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

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

Basically, I want to replace any journal name with the first letter of the name. For instance,

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

and etc.

+11
source share
2 answers

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

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

.1 sets the field width to no more than one character, trimming 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 documentation for line formatting operations :

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

  1. [...] Accuracy determines the maximum number of characters used.
+21
source

If you want a completely different level name, use logging.addLevelName

 logging.addLevelName(logging.DEBUG, 'DETAILED') logging.addLevelName(logging.INFO, 'GENERAL') 
0
source

Source: https://habr.com/ru/post/979528/


All Articles