在Python中重命名日志文件,同时文件继续写入任何其他日志
我正在使用Python日志记录器机制来记录日志。我有两种日志, 一个是旋转日志(log1、log2、log3…)和一个名为json.log的非旋转日志(顾名思义,其中包含json日志)。 日志文件在服务器启动时创建,在应用关闭时关闭 一般来说,我试图做的是:当我按下页面上的导入按钮时,将所有json日志保存在sqlite db上 我面临的问题是: 当我尝试像这样重命名json.log文件时:在Python中重命名日志文件,同时文件继续写入任何其他日志,python,json,logging,rename,Python,Json,Logging,Rename,我正在使用Python日志记录器机制来记录日志。我有两种日志, 一个是旋转日志(log1、log2、log3…)和一个名为json.log的非旋转日志(顾名思义,其中包含json日志)。 日志文件在服务器启动时创建,在应用关闭时关闭 一般来说,我试图做的是:当我按下页面上的导入按钮时,将所有json日志保存在sqlite db上 我面临的问题是: 当我尝试像这样重命名json.log文件时: source_file = "./logs/json.log" snapshot_file = "./l
source_file = "./logs/json.log"
snapshot_file = "./logs/json.snapshot.log"
try:
os.rename(source_file, snapshot_file)
我得到windowsError:[Error 32]该进程无法访问该文件,因为它正被另一个进程使用
这是因为日志记录器一直在使用该文件。因此,我需要以某种方式“关闭”该文件,以便成功执行I/O操作。
问题是,这是不可取的,因为日志可能会丢失,直到文件关闭,然后重命名,然后“重新创建”
我想知道是否有人再次遇到这种情况,是否找到了任何切实可行的解决办法
我尝试了一些有效的方法,但似乎并不方便,也不确定是否安全,这样就不会丢失任何日志
我的代码是:
source_file = "./logs/json.log"
snapshot_file = "./logs/json.snapshot.log"
try:
logger = get_logger()
# some hackish way to remove the handler for json.log
if len(logger.handlers) > 2:
logger.removeHandler(logger.handlers[2])
if not os.path.exists(snapshot_file):
os.rename(source_file, snapshot_file)
try:
if type(logger.handlers[2]) == RequestLoggerHandler:
del logger.handlers[2]
except IndexError:
pass
# re-adding the logs file handler so it continues writing the logs
json_file_name = configuration["brew.log_file_dir"] + os.sep + "json.log"
json_log_level = logging.DEBUG
json_file_handler = logging.FileHandler(json_file_name)
json_file_handler.setLevel(json_log_level)
json_file_handler.addFilter(JSONLoggerFiltering())
json_file_handler.setFormatter(JSONFormatter())
logger.addHandler(json_file_handler)
... code continues to write the logs to the db and then delete the json.snapshot.file
until the next time the import button is pressed; then the snapshot is created again
only for writing the logs to the db.
我的日志文件的格式如下,仅供参考:
{'status': 200, 'actual_user': 1, 'resource_name': '/core/logs/process', 'log_level': 'INFO', 'request_body': None, ... }
提前感谢:)