【问题标题】:How to toggle Jupyter Notebook display logging如何切换 Jupyter Notebook 显示日志记录
【发布时间】:2019-06-12 06:49:45
【问题描述】:

我正在尝试将日志记录应用到 Jupyter Notebook 的 display(df) 功能。如何编辑代码的最后一行,以便仅在记录 INFO 处于活动状态时才显示数据框?目前显示日志记录是活动的还是非活动的。

import pandas as pd

logging.basicConfig(level=logging.INFO, format=' %(asctime)s - %(levelname)s - %(message)s')

filename = 'test.csv'
df=pd.read_csv(filename, index_col=None, encoding='utf-8')

logging.info(display(df))

【问题讨论】:

  • display(df) 在发送到logging.info() 之前被评估(并呈现到笔记本) - 它不是惰性评估,因此这种方法不起作用。等效于logging.info(print(df)) - print(df) 将始终输出。

标签: python logging jupyter-notebook


【解决方案1】:

目前显示记录是活跃还是不活跃。

我猜你是说当你改变logging.basicConfig 的参数level 时,结果不会随之改变。这也发生在我身上。在检查了logging - DocLogging basicConfig not creating log file when i run in pycharm? 之后,我能够得出一个解决方案:

for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

logging.basicConfig(format=' %(asctime)s - %(levelname)s - %(message)s')
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9]})

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.debug("\n"+str(df))
logger.info("\n"+str(df))
logger.warning("\n"+str(df))
logger.error("\n"+str(df))
logger.critical("\n"+str(df))

你可以和logger.setLevel(logging.DEBUG)一起玩,看看它是否有效。

因为display(df) 无论如何都会像@AChampion 所说的那样被调用,所以我使用"\n"+str(df) 替换display(df)

输出:

 2019-01-18 14:20:47,710 - DEBUG - 
   a  b  c
0  1  4  7
1  2  5  8
2  3  6  9
 2019-01-18 14:20:47,715 - INFO - 
   a  b  c
0  1  4  7
1  2  5  8
2  3  6  9
 2019-01-18 14:20:47,720 - WARNING - 
   a  b  c
0  1  4  7
1  2  5  8
2  3  6  9
 2019-01-18 14:20:47,724 - ERROR - 
   a  b  c
0  1  4  7
1  2  5  8
2  3  6  9
 2019-01-18 14:20:47,728 - CRITICAL - 
   a  b  c
0  1  4  7
1  2  5  8
2  3  6  9

【讨论】:

  • 谢谢。我可以让你上面的代码工作,但是我想使用 display(df) 因为它输出一个格式化的表格。
  • @Deskjokey 我已经添加了上面的结果,我认为它看起来就像display(df) 的结果。
  • Gah 我无法弄清楚重复日志记录发生了什么,但似乎在 IPython 中将流处理程序添加到根记录器?谢谢你指点我这个
猜你喜欢
  • 1970-01-01
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-29
  • 2021-11-07
  • 2017-04-01
相关资源
最近更新 更多