Reputation: 6186
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.
Upvotes: 31
Views: 10651
Reputation: 2577
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!
Upvotes: 0
Reputation: 817
If you want completely different levelname then use logging.addLevelName
logging.addLevelName(logging.DEBUG, 'DETAILED')
logging.addLevelName(logging.INFO, 'GENERAL')
Upvotes: 19
Reputation: 1122572
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 usingstr()
).
Notes: (6)
- [...] The precision determines the maximal number of characters used.
Upvotes: 51