3

我正在使用Pyramid和rq,並且我想將rq worker作業記錄在與我的金字塔應用程序相同的文件中。寫入與金字塔和rq相同的日誌文件

我的設置是這樣的:

development.ini

# regular pyramid setup here... 

[loggers] 
keys = root, main 

[handlers] 
keys = console, debuglog 

[formatters] 
keys = generic 

[logger_root] 
level = DEBUG 
handlers = console, debuglog 

[logger_main] 
level = DEBUG 
handlers = 
qualname = main 

[handler_debuglog] 
class = handlers.RotatingFileHandler 
args = ('%(here)s/__logs/pyramid_debug.log','a') 
level = DEBUG 
formatter = generic 

[formatter_generic] 
format = %(asctime)s %(levelname)-8s [%(name)s][%(threadName)s] %(message)s 

main.py

from bunch import Bunch 
from redis import Redis 
from rq import Queue, Worker 
from helpers.rqworker import run_worker 
from helpers.log import write_log 

write_log('info', 'APP STARTED.') 
q = Queue(connection=Redis()) 
req_obj = Bunch() 
req_obj.remote_addr = self.request.remote_addr 
job = q.enqueue(run_worker, req_obj, {'some_other': 'data'}) 
write_log('info', 'APP ENDED.') 

傭工/ rqworker.py

from helpers.log import write_log 

def run_worker(req, data): 
    write_log(req, 'debug', 'WORKER STARTED', separator=True) 

傭工/ log.py

import logging 
log = logging.getLogger(__name__) 


def write_log(request, loglevel, message=None, **kwargs): 
    msg = '[{0}] {1}'.format(request.remote_addr, message) 
    level = logging.getLevelName(loglevel.upper()) 

    if 'separator' in kwargs: 
     log.log(level, '='*40) 

    if message: 
     log.log(level, msg) 

    if 'stack' in kwargs: 
     log.log(level, '{0} EXCEPTION {0}'.format('*'*15)) 
     log.log(level, kwargs['stack']) 
     log.log(level, '{0} EXCEPTION END {0}'.format('*'*13)) 

當我運行我的應用程序,我不能看到rqworker.py日誌(可能是因爲它是一個單獨的線程),所以我不知道我怎麼可以(和有可能)實現寫入相同的日誌文件?

回答

0

這可能不是到OP有用了,但我已經能夠爲RQ工人的輸出重定向到一個自定義文件的方法是通過獲取這樣的記錄:

logger = logging.getLogger('rq.worker') 

你可以添加一個新的FileHandler這個記錄器上文件輸出,並更改格式太:

h = logging.FileHandler("/path/to/logfile.log") 
formatter = logging.Formatter(...) 
fh.setFormatter(formatter) 
logger.addHandler(fh) 

我一直沒能消除輸出的色彩,不過,這將導致日誌,打開時在文本編輯器中,會略微混雜ANSI顏色代碼。

請注意,這會將日誌記錄移除到控制檯。你也可以通過添加另一個處理程序來保持這一點。