将Python“打印"输出重定向到Logger [英] Redirect Python 'print' output to Logger

查看:556
本文介绍了将Python“打印"输出重定向到Logger的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python脚本,该脚本使用'Print'来打印到stdout.我最近通过Python Logger添加了日志记录,并希望通过日志记录使这些打印语句进入日志记录器(如果启用了日志记录).我不想修改或删除这些打印语句.

I have a Python script that makes use of 'Print' for printing to stdout. I've recently added logging via Python Logger and would like to make it so these print statements go to logger if logging is enabled. I do not want to modify or remove these print statements.

我可以通过执行'log.info("some info msg")'进行记录.我希望能够做这样的事情:

I can log by doing 'log.info("some info msg")'. I want to be able to do something like this:

if logging_enabled:
  sys.stdout=log.info
print("test")

如果启用了日志记录,则应该像记录log.info("test")一样记录"test".如果未启用日志记录,则应仅将测试"打印到屏幕上.

If logging is enabled, "test" should be logged as if I did log.info("test"). If logging isn't enabled, "test" should just be printed to the screen.

这可能吗?我知道我可以用类似的方式将stdout定向到文件(请参阅:将打印重定向到日志文件)

Is this possible? I know I can direct stdout to a file in a similar manner (see: redirect prints to log file)

推荐答案

您有两个选择:

  1. 打开一个日志文件,并用它而不是函数替换sys.stdout:

  1. Open a logfile and replace sys.stdout with it, not a function:

log = open("myprog.log", "a")
sys.stdout = log

>>> print("Hello")
>>> # nothing is printed because it goes to the log file instead.

  • 用您的日志功能替换打印:

  • Replace print with your log function:

    # If you're using python 2.x, uncomment the next line
    #from __future__ import print_function
    print = log.info
    
    >>> print("Hello!")
    >>> # nothing is printed because log.info is called instead of print
    

  • 这篇关于将Python“打印"输出重定向到Logger的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆