遇到打开文件描述符消息时,Python日志记录失败

时间:2011-07-11 07:33:11

标签: python logging subprocess file-descriptor lvm

我有以下Python代码在Linux机器上创建lvm快照。

#!/usr/bin/env python3.1

import subprocess
import logging
logging.basicConfig(filename='/var/log/lvsnap.log', filemode='w', level=logging.DEBUG)

lvm_vg = 'vg00-crunchbang'
lvm_name = 'root'
lvm_snapshot_size = '100'

def lvmCreateSnapshot(lvm_vg, lvm_name, lvm_snapshot_size):
    return subprocess.check_call(['lvcreate', '-s', '-l', '+' + lvm_snapshot_size + '%FREE', '-n', lvm_name + '-snapshot', lvm_vg + '/' + lvm_name])

logging.debug('logging is working before lvm snapshot')

''' create lvm snapshot '''
lvm_create_snapshot = lvmCreateSnapshot(lvm_vg, lvm_name, lvm_snapshot_size)
if lvm_create_snapshot:
    logging.debug('create lvm snapshot of %s/%s exited with status %s', lvm_vg, lvm_name, lvm_create_snapshot)

logging.debug('logging is working after lvm snapshot')

lvmCreateSnapshot正常运行并以0退出,然后在if语句中运行logging.debug行。 但是这不会发生,而是从脚本中收到以下输出:

> /tmp/lvmsnap.py 
File descriptor 3 (/var/log/lvsnap.log) leaked on lvcreate invocation. Parent PID 7860: python3.1
Logical volume "root-snapshot" created
>

日志的输出是:

> cat /var/log/lvsnap.log 
DEBUG:root:logging is working before lvm snapshot
DEBUG:root:logging is working after lvm snapshot
>

正如您所看到的那样,缺少lvm logging.debug消息(它应该出现在我创建的2条测试日志消息之间)。

为什么会发生这种情况,我该如何解决?

1 个答案:

答案 0 :(得分:3)

您没有调用“缺失”logging.debug,因为lvmCreateSnapshot返回零,因此您的if条件永远不会满足。尝试

if lvm_create_snapshot:
    logging.debug('Error creating lvm snapshot of %s/%s, exited with status %s', lvm_vg, lvm_name, lvm_create_snapshot)
else:
    logging.debug('created lvm snapshot of %s/%s, lvm_vg, lvm_name)

以便成功else来电subprocess成功,if条件另有规定,或

if not lvm_create_snapshot:
    logging.debug('...debugging text...')

仅在subprocess返回错误时才输出调试消息。

编辑:

我刚刚查看了subprocess.check_call()的文档,请参阅http://docs.python.org/library/subprocess.html,其中指出如果子进程调用成功,subprocess.check_call将返回零,否则会引发CalledProcessError异常。因此,您必须使用通常的try / except块捕获此异常。以下内容应该足够了:

try:
    lvmCreateSnapshot(lvm_vg, lvm_name, lvm_snapshot_size)
    logging.debug('created lvm snapshot of %s/%s', lvm_vg, lvm_name)
except CalledProcessError as e:
    logging.debug('Error creating lvm snapshot of {0}/{1}. Return code was {2}'.format(lvm_vg,
        lvm_name, e.returncode))
    raise

最后加注是打印追溯。你当然可以使用类似return 1的东西。