Python:登录到文件并执行sys.stdout
我需要编写一个函数来登录到一个文件中(使用日志模块),同时在控制台上打印相同的内容 我得到的是:Python:登录到文件并执行sys.stdout,python,python-2.7,Python,Python 2.7,我需要编写一个函数来登录到一个文件中(使用日志模块),同时在控制台上打印相同的内容 我得到的是: def printScreenAndLog(msg): log = logging.getLogger() log.info(msg) now = str(datetime.datetime.now()) print now,"%s" % msg def main(): options, args = usage() log = logging.getLogge
def printScreenAndLog(msg):
log = logging.getLogger()
log.info(msg)
now = str(datetime.datetime.now())
print now,"%s" % msg
def main():
options, args = usage()
log = logging.getLogger("CMDR")
log.setLevel(logging.DEBUG)
fh = logging.FileHandler('cmdr.log')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
log.addHandler(fh)
printScreenAndLog("Testing")
if __name__ == "__main__":
main()
您是否尝试将日志记录级别设置为info而不是debug?
或者在PrintScreen和log函数中使用log.debug(msg)?此函数应满足您的要求:
def configure_logging():
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
# log to stdout
logging.basicConfig(level=logging.DEBUG, format=log_format)
# also log to file
formatter = logging.Formatter(log_format)
handler = logging.FileHandler("cmdr.log")
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
logging.getLogger('').addHandler(handler)