我知道如何使twisted使用python logging(docs)
但是普通的python日志记录仍然被吞噬。打印语句是可见的,但logger.warn('...')
不是。
我在我的库中使用此日志记录设置,我想使用twisted:
import logging
logger=logging.getLogger(os.path.basename(sys.argv[0]))
class Foo:
def foo(self):
logger.warn('...')
我不想更改我的库以使用扭曲日志记录,因为该库已经在许多不使用扭曲的项目中使用。
如果我谷歌解决这个问题,我只找到将扭曲的日志传递给python日志记录的解决方案。
如何查看我的库的日志记录(不更改它)?
答案 0 :(得分:0)
问题是Twisted是异步的,并且尽可能避免阻塞I / O.但是,stdlib日志记录不是异步的,因此它会阻塞I / O,因此这两者不能轻易混合。如果您例如,您可能能够实现某种程度的合作。使用QueueHandler
(在Python 3.2中的stdlib中引入并提到here,但通过logutils
项目可用于早期版本)。您可以使用此处理程序(仅此处理程序)来处理使用stdlib日志记录发送的事件,并且相应的QueueListener
可以使用Twisted(非阻塞)I / O调度接收的事件。它应该工作,因为如果没有有限的容量创建队列处理程序不应该阻塞,并假设I / O接收器可以足够快地摆脱事件(否则,内存将填满)。
答案 1 :(得分:0)
utils的/ log.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import logging.handlers
from logging.config import dictConfig
from twisted.python.failure import Failure
from twisted.python import log as twisted_log
logger = logging.getLogger(__name__)
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'loggers': {
'twisted':{
'level': 'ERROR',
}
}
}
def failure_to_exc_info(failure):
"""Extract exc_info from Failure instances"""
if isinstance(failure, Failure):
return (failure.type, failure.value, failure.getTracebackObject())
def configure_logging(logfile_path):
"""
Initialize logging defaults for Project.
:param logfile_path: logfile used to the logfile
:type logfile_path: string
This function does:
- Assign INFO and DEBUG level to logger file handler and console handler
- Route warnings and twisted logging through Python standard logging
"""
observer = twisted_log.PythonLoggingObserver('twisted')
observer.start()
dictConfig(DEFAULT_LOGGING)
default_formatter = logging.Formatter(
"[%(asctime)s] [%(levelname)s] [%(name)s] [%(funcName)s():%(lineno)s] [PID:%(process)d TID:%(thread)d] %(message)s",
"%d/%m/%Y %H:%M:%S")
file_handler = logging.handlers.RotatingFileHandler(logfile_path, maxBytes=10485760,backupCount=300, encoding='utf-8')
file_handler.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(default_formatter)
console_handler.setFormatter(default_formatter)
logging.root.setLevel(logging.DEBUG)
logging.root.addHandler(file_handler)
logging.root.addHandler(console_handler)
hello.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
logger = logging.getLogger(__name__)
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.resource import Resource
class BasicPage(Resource):
isLeaf = True
def render_GET(self, request):
logger.info("<html><body><h1>Basic Test</h1><p>This is a basic test page.</p></body></html>")
return "<html><body><h1>Basic Test</h1><p>This is a basic test page.</p></body></html>"
def hello():
logger.info("Basic web server started. Visit http://localhost:8000.")
root = BasicPage()
factory = Site(root)
reactor.listenTCP(8000, factory)
reactor.run()
exit()
main.py
def main():
configure_logging('logfilepath')
hello.hello()