Dim*_*dis 8 python logging tensorflow
当我运行代码时,Tensorflow使隐藏的日志消息不显示。
我已经尝试了以下内容,但是找不到使我的代码正常工作的方法。
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
Run Code Online (Sandbox Code Playgroud)
所以我的代码如下
import logging
import tensorflow as tf
logging.basicConfig(filename='example.log', level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
Run Code Online (Sandbox Code Playgroud)
我希望将调试消息放入我的文件example.log中,但是示例日志中什么也没出现。当我导入tensorflow时,消息不会出现,而当我不这样做时,它们会出现。
我需要同时使用tensorflow和日志记录,因为我使用的是现有代码。有没有办法让日志记录抑制Tensorflow?
两个事实:
logging.basicConfig 如果已经配置了根记录器,则什么都不做:
如果根记录器已经为其配置了处理程序,则此函数不执行任何操作。
tensorflow具有absl-py将尝试在导入时通过将 a 附加NullHandler到根处理程序来初始化日志记录的依赖项:
# The absl handler will always be attached to root, not the absl logger.
if not logging.root.handlers:
# Attach the absl handler at import time when there are no other handlers.
# Otherwise it means users have explicitly configured logging, and the absl
# handler will only be attached later in app.run(). For App Engine apps,
# the absl handler is not used.
logging.root.addHandler(_absl_handler)
Run Code Online (Sandbox Code Playgroud)
不知道为什么处理程序附加到根记录器而不是absl记录器,虽然 - 可能是一个错误或其他一些问题的解决方法。
所以问题是import tensorflow调用会import absl.logging导致早期的记录器配置。随后的调用(你的)logging.basicConfig将因此什么都不做。要解决此问题,您需要在导入之前配置日志记录tensorflow:
import logging
logging.basicConfig(filename='example.log', level=logging.DEBUG)
import tensorflow as tf
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
Run Code Online (Sandbox Code Playgroud)
经验法则:始终尽早调用您的日志记录配置。
如果您只想将默认日志写入文件,abseillogger 也可以这样做:
from absl import logging as absl_logging
absl_logging.get_absl_handler().use_absl_log_file(
program_name='mytool',
log_dir='/var/logs/'
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
426 次 |
| 最近记录: |