我在linux系统上使用标准的python(2.5.2)日志记录模块,特别是RotatingFileHandler.我的应用程序支持命令行界面和Web服务界面.我想同时写入同一个日志文件.但是,当日志文件被轮换时,新文件具有644权限,并且由Web服务器用户拥有,这阻止了命令行用户写入它.我是否可以指定新的日志文件在日志记录配置中或在日志记录初始化期间是否可以进行组写?
我已经查看了'模式'设置(r/w/a),但它似乎不支持任何文件权限.
小智 30
这是一个稍好的解决方案.这会覆盖使用的_open方法.在创建之前设置umask然后将其返回到原来的状态.
class GroupWriteRotatingFileHandler(logging.handlers.RotatingFileHandler):
def _open(self):
prevumask=os.umask(0o002)
#os.fdopen(os.open('/path/to/file', os.O_WRONLY, 0600))
rtv=logging.handlers.RotatingFileHandler._open(self)
os.umask(prevumask)
return rtv
Run Code Online (Sandbox Code Playgroud)
Cor*_*son 19
我使用扫描logging.handlers模块,但无法看到任何指定不同文件权限模式的方法.所以,我现在有一个解决方案,它基于将RotatingFileHandler扩展为自定义处理程序.一旦我发现创建一个很好的参考,它就相当轻松了.自定义处理程序的代码如下所示.
class GroupWriteRotatingFileHandler(handlers.RotatingFileHandler):
def doRollover(self):
"""
Override base class method to make the new log file group writable.
"""
# Rotate the file first.
handlers.RotatingFileHandler.doRollover(self)
# Add group write to the current permissions.
currMode = os.stat(self.baseFilename).st_mode
os.chmod(self.baseFilename, currMode | stat.S_IWGRP)
Run Code Online (Sandbox Code Playgroud)
我还发现,要从日志配置文件引用自定义处理程序,我必须将我的模块绑定到日志记录命名空间.做起来很简单,但很烦人.
from mynamespace.logging import custom_handlers
logging.custom_handlers = custom_handlers
Run Code Online (Sandbox Code Playgroud)
我觉得有用的参考资料: 绑定自定义处理程序和 创建自定义处理程序
| 归档时间: |
|
| 查看次数: |
11844 次 |
| 最近记录: |