在Python中,使用
import logging
logging.basicConfig(filename="logname",
filemode='a',
format='%(asctime)s,%(msecs)03d %(name)s %(levelname)s %(message)s',
datefmt='%D %H:%M:%S',
level=logging.DEBUG)
logging.getLogger().addHandler(logging.StreamHandler())
logging.info("=================================================")
logging.info("starting execution")
我能够在日志文件中正确地记录格式:
03/30/18 12:52:08,231 root INFO =================================================
03/30/18 12:52:08,232 root INFO starting execution
不幸的是,对于控制台,没有遵循格式:
Connected to pydev debugger (build 173.4674.37)
=================================================
starting execution
我需要编写什么才能使控制台输出格式化?
答案 0 :(得分:0)
python文档中的这个例子看起来就是诀窍https://docs.python.org/2/howto/logging-cookbook.html#logging-to-multiple-destinations
import logging
logging.basicConfig(filename="logname",
filemode='a',
format='%(asctime)s,%(msecs)03d %(name)s %(levelname)s %(message)s',
datefmt='%D %H:%M:%S',
level=logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
# set a format which is simpler for console use
formatter = logging.Formatter('%(asctime)s,%(msecs)03d %(name)s %(levelname)s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
logging.info("=================================================")
logging.info("starting execution")
提供以下控制台输出
2018-03-30 19:15:00,940,940 root INFO =================================================
2018-03-30 19:15:07,768,768 root INFO starting execution