我有一个脚本,执行数据库操作旁边一个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
实例;除非我在这里错过了一些东西。
啊,我明白了。我最终在运行时在单独的进程中运行了alembic命令。你的解决方案要好得多。谢谢。 – trendsetter37
这是一个很好的解决方案。我还想推荐我们使用Config实例化来设置我们的configure_logger值而不是'config.attributes'。即。 'config = Config('alembic.ini',attributes = {'configure_logger':False})' – Imjohsep