2012-02-23 43 views
5

Tôi có thể chuyển hướng tất cả đầu ra từ stdout tới trình ghi nhật ký mà tôi đã thiết lập với mô-đun chuẩn logging không? (Tôi có os.system gọi mà đầu ra tôi cũng muốn xem hoặc báo cáo in occational)Chuyển hướng stdout sang logger bằng Python

+2

Duplicate của http://stackoverflow.com/questions/975248/redirecting-sys-stdout-to-python-logging – synthesizerpatel

+0

Cảm ơn! Bằng cách nào đó các đề xuất tự động chỉ hiển thị chuyển hướng stdout cho các tệp ... – Gerenuk

Trả lời

4

Bạn có thể có thể tận dụng các gợi ý trong this post, tóm tắt dưới đây:

import logging 

class LoggerWriter: 
    def __init__(self, logger, level): 
     self.logger = logger 
     self.level = level 

    def write(self, message): 
     if message != '\n': 
      self.logger.log(self.level, message) 

def main(): 
    logging.basicConfig(level=logging.DEBUG) 
    logger = logging.getLogger("demo") 
    info_fp = LoggerWriter(logger, logging.INFO) 
    debug_fp = LoggerWriter(logger, logging.DEBUG) 
    print >> info_fp, "An INFO message" 
    print >> debug_fp, "A DEBUG message" 

if __name__ == "__main__": 
    main() 

Khi chạy, các bản in kịch bản:

INFO:demo:An INFO message 
DEBUG:demo:An DEBUG message 
Các vấn đề liên quan