我尝试在我的应用程序中使用日志记录模块;在阅读完文档后,我写了一些完整的代码:
class mainwin():
def start_logging(self , level):
logger = logging.getLogger('Rockdome:')
FORMAT = "***\n\n%s%(name)s [%(levelname)s]\nmodule: %(module)s\nMessage:%(message)s\n***"
logging.basicConfig(format=FORMAT, filename= "example.log" , filemode="w")
logger.setLevel(level)
self.logger = logger
def __init__(self ):
self.start_logging(logging.INFO)
self.pid = os.getpid()
with open('%s/.aria2/pid'%self.home , 'w') as p:
p.write(str(self.pid))
我得到以下内容:
***{'threadName': 'MainThread', 'name': 'Rockdome:', 'thread': -1221756160, 'created': 1412549164.939926, 'process': 7195, 'processName': 'MainProcess', 'args': (), 'module': 'mainwin', 'filename': 'mainwin.py', 'levelno': 20, 'exc_text': None, 'pathname': 'mainwin.py', 'lineno': 184, 'msg': 'Application started PID= 7195', 'exc_info': None, 'message': 'Application started PID= 7195', 'funcName': '__init__', 'relativeCreated': 178.4038543701172, 'levelname': 'INFO', 'msecs': 939.9259090423584}Rockdome: [INFO]
module: mainwin
Message:Application started PID= 7195
***
{}
之间的文本是logrecord对象本身。
为什么logrecord对象已写入logfile ??
问题是:如何获得此输出?
***
Rockdome: [INFO]
module: mainwin
Message:Application started PID= 7195
***
答案 0 :(得分:2)
您在格式字符串的开头只有一个额外的\n%s
。删除它们:
FORMAT = "***\n%(name)s [%(levelname)s]\nmodule: %(module)s\nMessage:%(message)s\n***"
一旦你这样做,你将获得正确的格式。额外的%s
特别会打印所有可能的logger
属性,这就是为什么您的消息与您想要的内容相距甚远。通过一些测试,您可以更好地了解那里发生的事情:
>>> d = {"test" : "abcdefg", "another" : "asdfasdf"}
>>> print "%(test)s" % d # What you wanted to do
abcdefg
>>> print "%s" % d # What you ended up doing
{'test': 'abcdefg', 'another': 'asdfasdf'}