动态切换日志存储文件夹

如何解决动态切换日志存储文件夹

我正在使用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')

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-