我有一个使用logging.FileHandler
打开文件的第三方模块,我想知道如何从文件名中找到它的fileno
。
third_party.py:
def setup_loging(logfile):
logFormatter = logging.Formatter(
"%(asctime)s [%(process)d] [%(name)-12.12s] "
"[%(levelname)-5.5s] %(message)s")
rootLogger = logging.getLogger()
rootLogger.setLevel(logging.NOTSET)
if logfile:
fileHandler = logging.FileHandler(logfile, mode="wt", encoding="utf-8")
fileHandler.setFormatter(logFormatter)
fileHandler.setLevel(logging.NOTSET)
rootLogger.addHandler(fileHandler)
consoleHandler = logging.StreamHandler(sys.stdout)
if verbose:
consoleHandler.setLevel(logging.DEBUG)
else:
consoleHandler.setLevel(logging.INFO)
consolelogFormatter = logging.Formatter(
"[%(name)-12.12s] [%(levelname)-5.5s] %(message)s")
consoleHandler.setFormatter(consolelogFormatter)
rootLogger.addHandler(consoleHandler)
my_script.py:
from third_party import setup_loging
setup_loging(logfile='/tmp/foo.log')
# How do I get the fileno for file /tmp/foo.log ?
# only way i know is doing: lsof /tmp/foo.log
print get_fileno_from_filename('/tmp/foo.log')
答案 0 :(得分:1)
尝试从stream
抓取FileHandler
属性,然后抓取stream
以获取文件对象:
def setup_loging(logfile):
# your code...
if logfile:
return fileHandler
logging_handler = setup_loging(logfile='/tmp/foo.log')
if logging_handler:
print("fileno: {}".format(logging_handler.stream.stream.fileno()))
有点hackish,但完成工作;)
P.S。如果您无法以任何方式修改脚本,您始终可以获取所有根日志记录处理程序(logging.getLogger().handlers
)并筛选它们,直到找到FileHandler,但可能有多个,所以请确保在获取其name
之前,请检查解压缩的文件对象的fileno()
属性。类似的东西:
import os
your_log_file = "/tmp/foo.log"
log_file_path = os.path.realpath(your_log_file) # make sure we have a full path
setup_loging(log_file_path) # call the third party
for handler in logging.getLogger().handlers:
if isinstance(handler, logging.FileHandler):
if handler.stream.stream.name == log_file_path:
print("{}, fileno: {}".format(log_file_path, handler.stream.stream.fileno()))
break