动态切换日志存储文件夹

问题描述

我正在使用Python的日志记录来记录应用程序中功能和其他动作的执行情况。日志文件存储在一个远程文件夹中,当我连接到VPN时可以自动访问该文件夹(例如\ remote \ directory)。这是正常情况,有99%的时间有连接并且日志存储没有错误

当VPN连接或Internet连接丢失并且日志临时存储在本地时,我需要一种解决方案。我认为每次尝试记录某些内容时,我都需要检查远程文件夹是否可访问。我找不到真正的解决方案,但我想我需要以某种方式修改FileHandler。

TLDR:您已经可以向下滚动到布鲁斯的答案和我的“更新”部分-这是我最近尝试解决的问题。

目前,我的处理程序设置如下:

log = logging.getLogger('general')
handler_error = logging.handlers.RotatingFileHandler(log_path+"\\error.log",'a',encoding="utf-8")
log.addHandler(handler_error)

这是设置日志路径的条件,但只能设置一次-初始化日志时。如果我认为正确,我希望每次

if (os.path.isdir(f"\\\\remote\\folder\\")):  # if remote is accessible
    log_path = f"\\\\remote\\folder\\dev\\{d.year}\\{month}\\"
    os.makedirs(os.path.dirname(log_path),exist_ok=True)  # create this month dir if it does not exist,logging does not handle that

else:  # if remote is not accesssible
    log_path = f"localFiles\\logs\\dev\\{d.year}\\{month}\\"
    log.debug("Cannot access the remote directory. Are you connected to the internet and the VPN?")

我找到了一个相关的线程,但是无法根据自己的需要进行调整:Dynamic filepath & filename for FileHandler in logger config file in python

我应该更深入地研究自定义处理程序还是还有其他方法?如果我可以调用自己的函数来执行日志记录,则可以在需要时更改日志记录路径(或者将记录器更改为具有适当路径的函数)就足够了。

更新: 根据布鲁斯的回答,我尝试过修改处理程序以适应我的需求。不幸的是,下面的代码无法在本地和远程路径之间切换 baseFilename 。记录器始终将日志保存到本地日志文件(在初始化记录器时已设置)。因此,我认为我修改 baseFilename 的尝试不起作用?

class HandlerCheckBefore(RotatingFileHandler):
    print("handler starts")
    def emit(self,record):

        calltime = date.today()

        if os.path.isdir(f"\\\\remote\\Path\\"):  # if remote is accessible

            print("handler remote")
            # create remote folders if not yet existent

            os.makedirs(os.path.dirname(f"\\\\remote\\Path\\{calltime.year}\\{calltime.strftime('%m')}\\"),exist_ok=True)
            if (self.level >= 20): # if error or above
                self.baseFilename = f"\\\\remote\\Path\\{calltime.year}\\{calltime.strftime('%m')}\\error.log"
            else:
                self.baseFilename = f"\\\\remote\\Path\\{calltime.year}\\{calltime.strftime('%m')}\\{calltime.strftime('%d')}-{calltime.strftime('%m')}.log"
            super().emit(record)

        else:  # save to local
            print("handler local")
            if (self.level >= 20): # error or above
                self.baseFilename = f"localFiles\\logs\\{calltime.year}\\{calltime.strftime('%m')}\\error.log"
            else:
                self.baseFilename = f"localFiles\\logs\\{calltime.year}\\{calltime.strftime('%m')}\\{calltime.strftime('%d')}-{calltime.strftime('%m')}.log"
            super().emit(record)

# init the logger
handler_error = HandlerCheckBefore(f"\\\\remote\\Path\\{calltime.year}\\{calltime.strftime('%m')}\\error.log",encoding="utf-8")
handler_error.setLevel(logging.ERROR)
handler_error.setFormatter(fmt)
log.addHandler(handler_error)

解决方法

解决此问题的最佳方法的确是为此创建一个自定义处理程序。您可以在每次写入之前检查目录是否仍然存在,也可以尝试在handleError中写入日志并处理由此产生的错误,当emit()期间发生异常时,所有记录程序都会调用该错误。我推荐前者。下面的代码显示了如何同时实现:

import os
import logging
from logging.handlers import RotatingFileHandler


class GrzegorzRotatingFileHandlerCheckBefore(RotatingFileHandler):
    def emit(self,record):
        if os.path.isdir(os.path.dirname(self.baseFilename)): # put appropriate check here
            super().emit(record)
        else:
            logging.getLogger('offline').error('Cannot access the remote directory. Are you connected to the internet and the VPN?')


class GrzegorzRotatingFileHandlerHandleError(RotatingFileHandler):
    def handleError(self,record):
        logging.getLogger('offline').error('Something went wrong when writing log. Probably remote dir is not accessible')
        super().handleError(record)


log = logging.getLogger('general')
log.addHandler(GrzegorzRotatingFileHandlerCheckBefore('check.log'))
log.addHandler(GrzegorzRotatingFileHandlerHandleError('handle.log'))

offline_logger = logging.getLogger('offline')
offline_logger.addHandler(logging.FileHandler('offline.log'))

log.error('test logging')