6

我正在使用logging这样的 Python 模块:

class InitLogging():
    def LogModule(self):
        self.Logger          = logging.getLogger("_TCP_Logger")
        self.Logger.LogLevel = logging.DEBUG
        self.Logger.setLevel(self.Logger.LogLevel)
        self.fh              = logging.FileHandler("Log.txt")
        self.fh.level        = logging.DEBUG
        self.formatter       = logging.Formatter('%(asctime)s %(levelname)s %(message)8s')
        self.Logger.addHandler(self.fh)        
        self.Logger.log(logging.INFO,"=====================================")
        self.Logger.log(logging.INFO,"Start Logging Module!!")
        self.Logger.log(logging.INFO,"=====================================")
        self.fh .setFormatter(self.formatter)
        self.Logger.log(logging.INFO,"Enrty to Logging Module!!")

class LogMsg(InitLogging):
    def Logit(self):
        self.LogModule()
        self.Logger.log(logging.DEBUG,'This is Debugging Message!!')
        self.Logger.log(logging.INFO,"This is Info Message!!")
        self.Logger.log(logging.WARNING,"This is WARNING Message!!")

LoggingInstance = LogMsg()
LoggingInstance.Logit()

当我运行我的代码时,我得到以下输出Log.txt

=====================================
Start Logging Module!!
=====================================

2013-03-20 17:51:35,135 INFO Enrty to Logging Module!!
2013-03-20 17:51:35,135 DEBUG This is Debugging Message!!
2013-03-20 17:51:35,135 INFO This is Info Message!
2013-03-20 17:51:35,135 WARNING This is WARNING Message!!

但我想将不同日志级别的消息对齐在一起,产生如下输出:

=====================================
Start Logging Module!!
=====================================
2013-03-20 17:51:35,135 INFO       Enrty to Logging Module!!
2013-03-20 17:51:35,135 DEBUG      This is Debugging Message!!
2013-03-20 17:51:35,135 INFO       This is Info Message!
2013-03-20 17:51:35,135 WARNING    This is WARNING Message!!

我怎样才能做到这一点?

4

1 回答 1

14

levelname向格式化程序的格式字符串中的字段添加宽度。

这是左对齐的:

self.formatter = logging.Formatter('%(asctime)s %(levelname)-10s %(message)s')

                         levelname
                       |----------|
2013-03-20 16:46:50,573 INFO       Enrty to Logging Module!!
2013-03-20 16:46:50,573 DEBUG      This is Debugging Message!!
2013-03-20 16:46:50,573 INFO       This is Info Message!!
2013-03-20 16:46:50,573 WARNING    This is WARNING Message!!

这是右对齐的:

self.formatter = logging.Formatter('%(asctime)s %(levelname)10s %(message)s')

                         levelname
                       |----------|
2013-03-20 16:51:04,648       INFO Enrty to Logging Module!!
2013-03-20 16:51:04,650      DEBUG This is Debugging Message!!
2013-03-20 16:51:04,650       INFO This is Info Message!!
2013-03-20 16:51:04,650    WARNING This is WARNING Message!!
                       |0123456789|
                       | width=10 |

字符串格式化文档

于 2013-03-20T12:48:12.980 回答