2017-02-23 132 views
3

我有一个脚本,执行数据库操作旁边一个alembic API调用来升级新创建的数据库头。我在使用模块级别记录器将日志写入文件的python logger实例时遇到问题。使用alembic.config.main重定向日志输出

然后脚本调用alembic.config.main(argv=alembic_args)来运行迁移。但是,使用原始记录器实例的alembic调用之后的每个日志语句都不会写入期望的日志文件。

这是一个重现行为的示例脚本。

#!/usr/bin/env python3 

import logging 
import os 

import alembic.config 

from .utilities import get_migration_dir 

logging.basicConfig(filename='test.log', 
        level=logging.DEBUG) 

CUR_DIR = os.path.dirname(__file__) 
LOG = logging.getLogger('so_log') 

LOG.info('Some stuff') 
LOG.info('More stuff') 

alembic_config = (
    '--raiseerr', 
    'upgrade', 'head' 
) 

os.chdir(get_migration_dir()) 

alembic.config.main(argv=alembic_config) 

os.chdir(CUR_DIR) 

LOG.debug('logging after alembic call.') 
LOG.debug('more logging after alembic call.') 
print('Code still running after alembic') 

日志文件输出

INFO:so_log:Some stuff 
INFO:so_log:More stuff 

标准输出

INFO [alembic.runtime.migration] Context impl PostgresqlImpl. 
INFO [alembic.runtime.migration] Will assume transactional DDL. 
print statement before alembic 
Code still running after alembic 

它好像在记录器实例,LOG,失去上下文或调用API蒸馏器后被指向别处。

此外,我试过在单独的线程中运行alembic调用,产生了相同的结果。我希望发生的事情应该是,在使用alembic进行迁移后,日志语句会继续写入指定文件,但这种情况不会发生。而且,它实际上打破了以后调用的任何代码的LOG实例;除非我在这里错过了一些东西。

回答

4

这是因为蒸馏器设置使用fileConfigalembic.ini日志,你可以看到它在你的env.py脚本:

# Interpret the config file for Python logging. 
# This line sets up loggers basically. 
fileConfig(config.config_file_name) 

这有效地将覆盖原来的记录器的配置。

为了避免这种情况,您可以简单地从env.py中删除此行,但是这会导致从控制台运行alembic时不会生成日志。

更强大的选项是通过alembic.command而不是alembic.config.main运行alembic命令。这样,您就可以在运行时覆盖蒸馏器配置:

from alembic.config import Config 
import alembic.command 

config = Config('alembic.ini') 
config.attributes['configure_logger'] = False 

alembic.command.upgrade(config, 'head') 

然后在env.py

if config.attributes.get('configure_logger', True): 
    fileConfig(config.config_file_name) 
+0

啊,我明白了。我最终在运行时在单独的进程中运行了alembic命令。你的解决方案要好得多。谢谢。 – trendsetter37

+1

这是一个很好的解决方案。我还想推荐我们使用Config实例化来设置我们的configure_logger值而不是'config.attributes'。即。 'config = Config('alembic.ini',attributes = {'configure_logger':False})' – Imjohsep