每次调用python中的日志记录模块时,都要调用一个函数



我想每次都调用一个函数,我使用python中的logging模块进行任何类型的日志记录。

如下所示,我不想在每个日志记录实例调用copyfiles,而是想看看是否有办法以某种方式甚至包装器将文件复制到文件处理程序。

from sys import argv
import shutil
import logging
logger = logging.getLogger('')
sh = logging.StreamHandler(sys.stdout)
logfile = 'logs/log-run-{}.log'.format(date.today().strftime('%d-%m-%Y'))
fh = logging.FileHandler(logfile)
formatter = logging.Formatter('[%(asctime)s] %(levelname)s 
[%(filename)s.%(funcName)s:%(lineno)d] 
%(message)s', datefmt='%a, %d %b %Y %H:%M:%S')
logger.setLevel(logging.INFO)
sh.setFormatter(formatter)
fh.setFormatter(formatter)
logger.addHandler(sh)
logger.addHandler(fh)
LOGPATH = args[1]
def copyfiles():
"""
Copy files to azure blob storage
"""
fh.flush()
shutil.copy(logfile, LOGPATH)
logging.info('test')
copyfiles()
logging.info('foobar')
copyfiles()

每次调用日志记录时,我都尝试调用复制文件,但最终没有找到。

如果你想知道我为什么要从日志中复制文件,这就是为什么。

目前我可以想到的是:

  • 通过将FileHandler的flush((继承到实用程序中来覆盖它类,如下面代码中所示的FlushCopyFileHandler类
  • 使用FlushCopyFileHandler类而不是使用FileHandler您所要做的就是调用这个重写的flush((

"quot;

from logging import FileHandler
from shutil
class FlushCopyFileHandler(FileHandler):

# These arguments are passed along to the parent class FileHandler.
def __init__(self, *args, **kwargs):
super(FlushCopyFileHandler, self).__init__(filename, *args, **kwargs)
self.copy_destination = "some default destination path"   # can also be set from args.

# When this flush() is called it will call the flush() of FileHandler class.
# After that it will call the shutil.copy() method.
def flush(self):
super().flush()
shutil.copy(self.filename, self.copy_destination)

# Use this to change destination path later on.
def set_copy_path(self, destination):
self.copy_destination = destination 

"quot">

最新更新