Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:登录到文件并执行sys.stdout_Python_Python 2.7 - Fatal编程技术网

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)