Helga
Helga

Reputation: 113

How to add alignment to python standard logger if I use [LOGLEVEL]?

I have logger code like this:

import logging

logger = logging.getLogger("simple_example")
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
formatter = logging.Formatter("%(asctime)-15s :: [%(levelname)8s] ::  %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)

logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")

Output (AS-IS):

2016-04-21 10:42:41,805 :: [   DEBUG] ::  debug message
2016-04-21 10:42:41,805 :: [    INFO] ::  info message
2016-04-21 10:42:41,805 :: [ WARNING] ::  warn message
2016-04-21 10:42:41,805 :: [   ERROR] ::  error message
2016-04-21 10:42:41,805 :: [CRITICAL] ::  critical message

How to have output like this?

2016-04-21 10:42:41,805 :: [DEBUG]   ::  debug message
2016-04-21 10:42:41,805 :: [INFO]    ::  info message
2016-04-21 10:42:41,805 :: [WARNING] ::  warn message
2016-04-21 10:42:41,805 :: [ERROR]   ::  error message
2016-04-21 10:42:41,805 :: [CRITICAL]::  critical message

If I use formater like this:

formatter = logging.Formatter("%(asctime)-15s :: %([levelname])8s ::  %(message)s")

I have error

KeyError: '[levelname]'

Upvotes: 1

Views: 2517

Answers (2)

ad22
ad22

Reputation: 375

This formatter should do the trick:

import logging

class LoggerFormatter(logging.Formatter):
    width = 10
    def format(self, record):
        level = record.levelname
        padding = self.width - len(level)
        time = self.formatTime(record, self.datefmt)
        return '%s :: [%s] %s :: %s' % (time, level, ''.ljust(padding), record.getMessage())

Upvotes: 1

Suresh Jaganathan
Suresh Jaganathan

Reputation: 537

After lot of investigation there is no straight way to do the formatting as you expect, unless to use custom formatter.

import logging

class MyFormatter(logging.Formatter):
    width = 24
    datefmt='%Y-%m-%d %H:%M:%S'

    def format(self, record):
       record.message = record.getMessage()
       s = "%s :: %-10s :: %s" % (self.formatTime(record, self.datefmt), "[" + record.levelname + "]", record.getMessage())
       if record.exc_info:
         # Cache the traceback text to avoid converting it multiple times
         # (it's constant anyway)
         if not record.exc_text:
            record.exc_text = self.formatException(record.exc_info)
       if record.exc_text:
         if s[-1:] != "\n":
            s = s + "\n"
         s = s + record.exc_text
       return s


logger = logging.getLogger('simple_example')
#logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = MyFormatter()
ch.setFormatter(formatter)
logger.addHandler(ch)

logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")

Thanks to the post Logger custom formatter

Upvotes: 1

Related Questions