我正在使用Python的logging
模块:
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!!
我该怎么做?
答案 0 :(得分:9)
在格式化程序的格式字符串中为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 |