动态文件路径和python记录器配置文件中FileHandler的文件名 [英] Dynamic filepath & filename for FileHandler in logger config file in python

查看:328
本文介绍了动态文件路径和python记录器配置文件中FileHandler的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python日志配置文件,文件格式如下.

I have a python log config file with a filehandler of the below form.

[handler_filelog]
class: FileHandler
args = ('/var/tmp/log/client.log','a')

相反,我需要以下形式(动态生成的路径).

Instead, I need it in the below form (dynamically generated path).

[handler_filelog]
class: FileHandler
args = ('/var/tmp/log_<unique_string>/client.log','a')

该程序的多个实例可能正在运行,因此将使用无冲突的日志路径和文件. 记录程序一旦设置就无需更改,直到程序执行结束.

Multiple instances of the program may be running and hence non-conflicting log paths and files are to be used. The logger once setup need not change till end of program execution.

有没有一种使用配置文件方法来处理此问题的方法? 我不希望自己创建记录器/处理程序/格式化程序,因为我的日志配置文件包含许多此类记录器,并且基于配置文件的方法要好得多.

Is there a way to handle this using the config file approach? I am not keen on resorting to creating the loggers/handlers/formatters by myself since my log config file has many of these and config file based approach is much nicer.

(更新:我正在使用python 2.4)

(Update: I am using python 2.4)

推荐答案

这可以满足您的需求.您应该首先扩展FileHandler类.将其放在文件中,例如配置文件目录中的myHandler.py:

This does what you need. You should first extend the FileHandler class. Place this in a file, say myHandler.py in your config file's directory:

import logging
import random
import os
class myFileHandler(logging.FileHandler):
    def __init__(self,path,fileName,mode):
        r = random.randint(1,100000)
        path = path+"/log_"+str(r)
        os.mkdir(path)
        super(myFileHandler,self).__init__(path+"/"+fileName,mode)

然后在配置文件中,您可以像这样使用此自定义FileHandler

And then in the config file, you can use this custom FileHandler like this

class: myHandler.myFileHandler
args = ('/var/tmp','client.log','a')

我在我的机器上测试了这个

I tested this one on my machine

这篇关于动态文件路径和python记录器配置文件中FileHandler的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆