2017-02-23 140 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