使Python日志logging器除了日志之外还将所有消息输出到标准输出

有没有办法让Python日志logging使用logging模块自动输出的东西标准输出除了他们应该去的日志文件? 例如,我想所有的调用logger.warninglogger.criticallogger.error到他们预期的地方,但除此之外总是复制到stdout 。 这是为了避免重复消息,如:

 mylogger.critical("something failed") print "something failed" 

所有的日志输出都由处理程序处理; 只需将一个logging.StreamHandler()添加到根logging器。

以下是configurationstream处理程序(使用stdout而不是默认stderr )并将其添加到根logging器的示例:

 import logging import sys root = logging.getLogger() root.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) root.addHandler(ch) 

最简单的方法:

 import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) 

可以使用多个处理程序。

 import logging import auxiliary_module # create logger with 'spam_application' log = logging.getLogger('spam_application') log.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # create file handler which logs even debug messages fh = logging.FileHandler('spam.log') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) log.addHandler(fh) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.ERROR) ch.setFormatter(formatter) log.addHandler(ch) log.info('creating an instance of auxiliary_module.Auxiliary') a = auxiliary_module.Auxiliary() log.info('created an instance of auxiliary_module.Auxiliary') log.info('calling auxiliary_module.Auxiliary.do_something') a.do_something() log.info('finished auxiliary_module.Auxiliary.do_something') log.info('calling auxiliary_module.some_function()') auxiliary_module.some_function() log.info('done with auxiliary_module.some_function()') # remember to close the handlers for handler in log.handlers: handler.close() log.removeFilter(handler) 

请参阅: https : //docs.python.org/2/howto/logging-cookbook.html

login到文件和stderr最简单的方法:

  import logging logging.basicConfig(filename="logfile.txt") stderrLogger=logging.StreamHandler() stderrLogger.setFormatter(logging.Formatter(logging.BASIC_FORMAT)) logging.getLogger().addHandler(stderrLogger) 

你可以为file和stdout创build两个处理程序,然后用basicConfig handlers参数创build一个logging器。 如果您为这两个处理程序具有相同的log_level和format输出,则它可能很有用:

 import logging import sys file_handler = logging.FileHandler(filename='tmp.log') stdout_handler = logging.StreamHandler(sys.stdout) handlers = [file_handler, stdout_handler] logging.basicConfig( level=logging.DEBUG, format='[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s', handlers=handlers ) logger = logging.getLogger('LOGGER_NAME') 

hackish,但更简单:

 def print_n_log(msg,f): f.write(msg + "\n") print msg f = open("log_output.txt","w") 

那么每当你需要打印+logging一些东西只是打电话

 print_n_log("my message, hark!", f) 

然后在脚本的结尾closures日志文件:

 f.close()