Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to right align level field in Python logging.Formatter

I'm currently trying to right align the logging level field in my Python logger so that output such as:

[2011-10-14 13:47:51] [DEBUG] --- starting... (smtphandlers.py:96) [2011-10-14 13:47:51] [INFO] --- first things first... (smtphandlers.py:97) [2011-10-14 13:47:51] [WARNING] --- about to end... (smtphandlers.py:98) [2011-10-14 13:47:51] [DEBUG] --- ending (smtphandlers.py:99) 

instead looks like:

[2011-10-14 13:47:51] [   DEBUG] --- starting... (smtphandlers.py:96) [2011-10-14 13:47:51] [    INFO] --- first things first... (smtphandlers.py:97) [2011-10-14 13:47:51] [ WARNING] --- about to end... (smtphandlers.py:98) [2011-10-14 13:47:51] [   DEBUG] --- ending (smtphandlers.py:99) 

The format line for the first block is:

logging.Formatter("[%(asctime)s] [%(levelname)s] --- %(message)s (%(filename)s:%(lineno)s)", "%Y-%m-%d %H:%M:%S") 

If I know the max level length is 8 (eg: CRITICAL), then I'll right align to 8 spaces. I'm trying to figure out how to achieve this. The following fails because "%(levelname)s" is more than 8 characters (the substitution doesn't happen until later). If I use something like "{0:>20}".format"%(levelname)s", then it works, but that is more padding than I need or want.

logging.Formatter("[%(asctime)s] [" + "{0:>8}".format"%(levelname)s" + "] --- %(message)s (%(filename)s:%(lineno)s)", "%Y-%m-%d %H:%M:%S") 

Short of subclassing Formatter, anyone have a way to achieve this?

like image 468
stephen_liu Avatar asked Oct 14 '11 18:10

stephen_liu


People also ask

How do you right align a column in Python?

You can use the :> , :< or :^ option in the f-format to left align, right align or center align the text that you want to format. We can use the fortmat() string function in python to output the desired text in the order we want.

How do you right justify output in Python?

Note: If you want to right justify the string, use ljust().

What is level in logging in Python?

Python Logging Levels There are six log levels in Python; each level is associated with an integer that indicates the log severity: NOTSET=0, DEBUG=10, INFO=20, WARN=30, ERROR=40, and CRITICAL=50. All the levels are rather straightforward (DEBUG < INFO < WARN ) except NOTSET, whose particularity will be addressed next.


2 Answers

Like this:

logging.Formatter("[%(asctime)s] [%(levelname)8s] --- %(message)s (%(filename)s:%(lineno)s)", "%Y-%m-%d %H:%M:%S") 
like image 87
retracile Avatar answered Sep 24 '22 10:09

retracile


Try with this format line :

logging.Formatter("[%(asctime)s] [%(levelname)8s] --- %(message)s (%(filename)s:%(lineno)s)", "%Y-%m-%d %H:%M:%S") 

python logger formatter use the standard python string formatting rules

like image 27
Cédric Julien Avatar answered Sep 22 '22 10:09

Cédric Julien