如果我使用[LOGLEVEL],如何添加对齐python标准记录器?

时间:2016-04-21 08:03:48

标签: python logging

我有这样的记录器代码:

static int count=0;// Global Variable declare somewhere at the top 

protected void bttnAdd_Click(object sender, EventArgs e)
        {
            count++;

            if (count > 6)
            {
                lblBet.Text = count.ToString();
            }
            else
            {
                count = 0;
            }
        }

输出(AS-IS):

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")

如何输出这样的?

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

如果我使用这样的formater:

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

我有错误

  

KeyError:' [levelname]'

2 个答案:

答案 0 :(得分:1)

经过大量调查后,没有直接的方式来进行格式化,除非使用自定义格式化程序。

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")

感谢帖子Logger custom formatter

答案 1 :(得分:1)

这个格式化器应该可以解决这个问题:

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())