Python有条件地记录到不同的目的地

问题描述

我正在Python 3.8中使用logging登录文件并sysout

当前,日志同时进入文件和sysout。但是我想有条件地登录到其中任何一个

我当前的代码是:

logpath = constants.LOGS_LOCATION

fileHandler = RotatingFileHandler(logpath,maxBytes = 500000,backupCount = 10)
localLogFormatter = logging.Formatter("%(asctime)s [%(levelname)s] %(filename)s - %(funcName)s - %(message)s")
fileHandler.setFormatter(localLogFormatter)

stdoutHandler = logging.StreamHandler(sys.stdout)
formatter = MyJsonFormatter()
stdoutHandler.setFormatter(formatter)

logging.root.handlers = []
logging.basicConfig(
    level=logging.INFO,handlers=[
        fileHandler,stdoutHandler
    ]
)

所以当我这样做时:

logging.info("goes to both file and sysout")

以上内容同时适用于文件和sysout,但是我希望根据我的业务需求将日志记录到文件或sysout。

我该如何实现?是否可以通过参数设置或其他记录器完成?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)