有同样的问题,但解决方案不适用于 iPython,因为 QtConsole 会自动创建一个没有级别集的处理程序:
import logging
root = logging.getLogger()
root.handlers
Out: [<StreamHandler <stderr> (NOTSET)>]
结果 iPython 将 DEBUG 和 INFO 都打印到控制台,尽管我的文件处理程序和流处理程序具有不同的级别。
该线程为我指出了这个问题:Logging module does not print in IPython
我制作了一个名为 custom_logging.py 的辅助模块(这个堆栈线程帮助很大!),以便在其他模块中更方便地进行日志记录:
import logging
from pathlib import Path
import sys
def _add_stream_handler(logger: logging.Logger):
stream_handler = logging.StreamHandler()
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging.INFO)
logger.addHandler(stream_handler)
return logger
def _add_file_handler(logger: logging.Logger, log_path: Path):
file_handler = logging.FileHandler(log_path, mode='w')
formatter = logging.Formatter(
fmt='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)
logger.addHandler(file_handler)
return logger
def create_logger(root_dir: Path, caller: str) -> logging.Logger:
log_path = root_dir / 'logs' / f'{caller}.log'
logger = logging.getLogger(caller)
root = logging.getLogger()
logger.setLevel(logging.DEBUG)
# If haven't already launched handlers...
if not len(logger.handlers):
_add_file_handler(logger=logger, log_path=log_path)
_add_stream_handler(logger=logger)
logger.info('Logging started.')
# Delete the Qtconsole stderr handler
# ... as it automatically logs both DEBUG & INFO to stderr
if root.handlers:
root.handlers = []
return logger
def log_dataframe(df, logger: logging.Logger, name: str = "DataFrame") -> None:
logger.debug(
f'''{name} head:\n {df.head()}\n----------\n''')
def log_dataframes(*args, logger: logging.Logger) -> None:
for gdf in args:
logger.debug(
f'''DataFrame head:\n {gdf.head()}\n----------\n''')
可以通过以下方式使用其功能:
from custom_logging import create_logger, log_dataframe
或者import custom_logging
等等custom_logging.create_logger()
。
另请参阅官方日志记录手册中的“多个处理程序和格式化程序”和“记录到多个目的地”部分:
https ://docs.python.org/3/howto/logging-cookbook.html#logging-cookbook