本文整理汇总了Python中twisted.python.log.PythonLoggingObserver方法的典型用法代码示例。如果您正苦于以下问题:Python log.PythonLoggingObserver方法的具体用法?Python log.PythonLoggingObserver怎么用?Python log.PythonLoggingObserver使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.python.log
的用法示例。
在下文中一共展示了log.PythonLoggingObserver方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
# 需要导入模块: from twisted.python import log [as 别名]
# 或者: from twisted.python.log import PythonLoggingObserver [as 别名]
def setUp(self):
rootLogger = logging.getLogger("")
originalLevel = rootLogger.getEffectiveLevel()
rootLogger.setLevel(logging.DEBUG)
@self.addCleanup
def restoreLevel():
rootLogger.setLevel(originalLevel)
self.hdlr, self.out = handlerAndBytesIO()
rootLogger.addHandler(self.hdlr)
@self.addCleanup
def removeLogger():
rootLogger.removeHandler(self.hdlr)
self.hdlr.close()
self.lp = log.LogPublisher()
self.obs = log.PythonLoggingObserver()
self.lp.addObserver(self.obs.emit)
示例2: test_startStopObserver
# 需要导入模块: from twisted.python import log [as 别名]
# 或者: from twisted.python.log import PythonLoggingObserver [as 别名]
def test_startStopObserver(self):
"""
Test that start and stop methods of the observer actually register
and unregister to the log system.
"""
oldAddObserver = log.addObserver
oldRemoveObserver = log.removeObserver
l = []
try:
log.addObserver = l.append
log.removeObserver = l.remove
obs = log.PythonLoggingObserver()
obs.start()
self.assertEqual(l[0], obs.emit)
obs.stop()
self.assertEqual(len(l), 0)
finally:
log.addObserver = oldAddObserver
log.removeObserver = oldRemoveObserver
示例3: test_inheritance
# 需要导入模块: from twisted.python import log [as 别名]
# 或者: from twisted.python.log import PythonLoggingObserver [as 别名]
def test_inheritance(self):
"""
Test that we can inherit L{log.PythonLoggingObserver} and use super:
that's basically a validation that L{log.PythonLoggingObserver} is
new-style class.
"""
class MyObserver(log.PythonLoggingObserver):
def emit(self, eventDict):
super(MyObserver, self).emit(eventDict)
obs = MyObserver()
l = []
oldEmit = log.PythonLoggingObserver.emit
try:
log.PythonLoggingObserver.emit = l.append
obs.emit('foo')
self.assertEqual(len(l), 1)
finally:
log.PythonLoggingObserver.emit = oldEmit
示例4: test_startStopObserver
# 需要导入模块: from twisted.python import log [as 别名]
# 或者: from twisted.python.log import PythonLoggingObserver [as 别名]
def test_startStopObserver(self):
"""
Test that start and stop methods of the observer actually register
and unregister to the log system.
"""
oldAddObserver = log.addObserver
oldRemoveObserver = log.removeObserver
l = []
try:
log.addObserver = l.append
log.removeObserver = l.remove
obs = log.PythonLoggingObserver()
obs.start()
self.assertEquals(l[0], obs.emit)
obs.stop()
self.assertEquals(len(l), 0)
finally:
log.addObserver = oldAddObserver
log.removeObserver = oldRemoveObserver
示例5: test_inheritance
# 需要导入模块: from twisted.python import log [as 别名]
# 或者: from twisted.python.log import PythonLoggingObserver [as 别名]
def test_inheritance(self):
"""
Test that we can inherit L{log.PythonLoggingObserver} and use super:
that's basically a validation that L{log.PythonLoggingObserver} is
new-style class.
"""
class MyObserver(log.PythonLoggingObserver):
def emit(self, eventDict):
super(MyObserver, self).emit(eventDict)
obs = MyObserver()
l = []
oldEmit = log.PythonLoggingObserver.emit
try:
log.PythonLoggingObserver.emit = l.append
obs.emit('foo')
self.assertEquals(len(l), 1)
finally:
log.PythonLoggingObserver.emit = oldEmit
示例6: logger
# 需要导入模块: from twisted.python import log [as 别名]
# 或者: from twisted.python.log import PythonLoggingObserver [as 别名]
def logger():
try:
if 'ANCHORE_LOGFILE' in os.environ:
thefile = os.environ['ANCHORE_LOGFILE']
else:
thefile = "anchore-general.log"
except:
thefile = "anchore-general.log"
f = logfile.LogFile(thefile, '/var/log/', rotateLength=10000000, maxRotatedFiles=10)
log_observer = log.FileLogObserver(f)
return log_observer.emit
#def logger():
# return log.PythonLoggingObserver().emit
示例7: __init__
# 需要导入模块: from twisted.python import log [as 别名]
# 或者: from twisted.python.log import PythonLoggingObserver [as 别名]
def __init__(self):
self.safe_logging = True
observer = log.PythonLoggingObserver('obfslogger')
observer.start()
# Create the default log handler that logs to stdout.
self.obfslogger = logging.getLogger('obfslogger')
self.default_handler = logging.StreamHandler(sys.stdout)
self.set_formatter(self.default_handler)
self.obfslogger.addHandler(self.default_handler)
self.obfslogger.propagate = False
示例8: configure_logging
# 需要导入模块: from twisted.python import log [as 别名]
# 或者: from twisted.python.log import PythonLoggingObserver [as 别名]
def configure_logging(settings=None, install_root_handler=True):
"""
Initialize logging defaults for Scrapy.
:param settings: settings used to create and configure a handler for the
root logger (default: None).
:type settings: dict, :class:`~scrapy.settings.Settings` object or ``None``
:param install_root_handler: whether to install root logging handler
(default: True)
:type install_root_handler: bool
This function does:
- Route warnings and twisted logging through Python standard logging
- Assign DEBUG and ERROR level to Scrapy and Twisted loggers respectively
- Route stdout to log if LOG_STDOUT setting is True
When ``install_root_handler`` is True (default), this function also
creates a handler for the root logger according to given settings
(see :ref:`topics-logging-settings`). You can override default options
using ``settings`` argument. When ``settings`` is empty or None, defaults
are used.
"""
if not sys.warnoptions:
# Route warnings through python logging
logging.captureWarnings(True)
observer = twisted_log.PythonLoggingObserver('twisted')
observer.start()
dictConfig(DEFAULT_LOGGING)
if isinstance(settings, dict) or settings is None:
settings = Settings(settings)
if settings.getbool('LOG_STDOUT'):
sys.stdout = StreamLogger(logging.getLogger('stdout'))
if install_root_handler:
install_scrapy_root_handler(settings)
示例9: setup_logging
# 需要导入模块: from twisted.python import log [as 别名]
# 或者: from twisted.python.log import PythonLoggingObserver [as 别名]
def setup_logging(cfg):
log_format = (
"%(asctime)s - %(name)s - %(lineno)d - %(levelname)s"
" - %(message)s"
)
formatter = logging.Formatter(log_format)
logPath = cfg.get('general', "log.path")
if logPath != '':
handler = logging.handlers.TimedRotatingFileHandler(
logPath, when='midnight', backupCount=365
)
handler.setFormatter(formatter)
def sighup(signum, stack):
logger.info("Closing log file due to SIGHUP")
handler.doRollover()
logger.info("Opened new log file due to SIGHUP")
else:
handler = logging.StreamHandler()
handler.setFormatter(formatter)
rootLogger = logging.getLogger('')
rootLogger.setLevel(cfg.get('general', 'log.level'))
rootLogger.addHandler(handler)
observer = log.PythonLoggingObserver()
observer.start()
示例10: process_nmap_commands
# 需要导入模块: from twisted.python import log [as 别名]
# 或者: from twisted.python.log import PythonLoggingObserver [as 别名]
def process_nmap_commands(loggerName):
""" Main function. Here we set up the environment, factory, interface, and port """
global nmapCommandsFile
global nmapCommand
global port
global mlog
global verboseLevel
global clientTimeout
observer = log.PythonLoggingObserver(loggerName)
observer.start()
# Create the factory
factory = Factory()
factory.protocol = NmapServerProtocol
# Create the time based print
loop = task.LoopingCall(show_info)
loop.start(5.0) # call every second
# Create the time based file read
loop2 = task.LoopingCall(read_file_and_fill_nmap_variable)
loop2.start(30.0) # call every second
# To mark idle clients as hold
loop3 = task.LoopingCall(timeout_idle_clients)
loop3.start(clientTimeout) # call every second
# Create the reactor
reactor.listenSSL(port, factory, ServerContextFactory(), interface=interface)
reactor.run()
示例11: setUp
# 需要导入模块: from twisted.python import log [as 别名]
# 或者: from twisted.python.log import PythonLoggingObserver [as 别名]
def setUp(self):
self.out = StringIO()
rootLogger = logging.getLogger("")
self.originalLevel = rootLogger.getEffectiveLevel()
rootLogger.setLevel(logging.DEBUG)
self.hdlr = logging.StreamHandler(self.out)
fmt = logging.Formatter(logging.BASIC_FORMAT)
self.hdlr.setFormatter(fmt)
rootLogger.addHandler(self.hdlr)
self.lp = log.LogPublisher()
self.obs = log.PythonLoggingObserver()
self.lp.addObserver(self.obs.emit)
示例12: connect
# 需要导入模块: from twisted.python import log [as 别名]
# 或者: from twisted.python.log import PythonLoggingObserver [as 别名]
def connect(server, password=None,
factory_class=VNCDoToolFactory, proxy=ThreadedVNCClientProxy, timeout=None):
""" Connect to a VNCServer and return a Client instance that is usable
in the main thread of non-Twisted Python Applications, EXPERIMENTAL.
>>> from vncdotool import api
>>> with api.connect('host') as client
>>> client.keyPress('c')
You may then call any regular VNCDoToolClient method on client from your
application code.
If you are using a GUI toolkit or other major async library please read
http://twistedmatrix.com/documents/13.0.0/core/howto/choosing-reactor.html
for a better method of intergrating vncdotool.
"""
if not reactor.running:
global _THREAD
_THREAD = threading.Thread(target=reactor.run, name='VNCPic',
kwargs={'installSignalHandlers': False})
_THREAD.daemon = True
_THREAD.start()
observer = PythonLoggingObserver()
observer.start()
factory = factory_class()
if password is not None:
factory.password = password
family, host, port = command.parse_server(server)
client = proxy(factory, timeout)
client.connect(host, port=port, family=family)
return client
示例13: __init__
# 需要导入模块: from twisted.python import log [as 别名]
# 或者: from twisted.python.log import PythonLoggingObserver [as 别名]
def __init__(self):
self._log_observer = log.PythonLoggingObserver()
self._log_observer.start()
示例14: initialize_logger
# 需要导入模块: from twisted.python import log [as 别名]
# 或者: from twisted.python.log import PythonLoggingObserver [as 别名]
def initialize_logger(self, to_stdout=False):
if to_stdout:
handler = logging.StreamHandler(stream=sys.stdout)
startLogging(sys.stdout)
else:
handler = DequeHandler(self.log_deque)
observer = PythonLoggingObserver()
observer.start()
fmt = "%(asctime)s %(levelname)s %(funcName)s %(message)s"
handler.setFormatter(logging.Formatter(fmt))
logger = logging.getLogger()
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
logging.debug("Hello World!")
示例15: startWebServer
# 需要导入模块: from twisted.python import log [as 别名]
# 或者: from twisted.python.log import PythonLoggingObserver [as 别名]
def startWebServer(options, config):
# import pdb; pdb.set_trace()
# Extract properties from config
log_dir = str(config["configuration"]["log_dir"])
content = str(config["configuration"]["content"])
# twisted expects byte for uris.
endpoint = str(config["configuration"]["endpoint"]).encode('utf-8')
host = str(config["configuration"]["host"])
port = int(config["configuration"]["port"])
sanitize = config["configuration"]["sanitize"]
# Setup logging
logFileName = log_dir + os.sep + "launcherLog.log"
formatting = '%(asctime)s:%(levelname)s:%(name)s:%(message)s'
logging.basicConfig(level=logging.DEBUG, filename=logFileName, filemode='w', format=formatting)
observer = log.PythonLoggingObserver()
observer.start()
if options.debug:
console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.INFO)
formatter = logging.Formatter(formatting)
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
# Initialize web resource
web_resource = File(content) if (len(content) > 0) else resource.Resource()
# Attach launcher
web_resource.putChild(endpoint, LauncherResource(options, config))
# Check if launcher should act as a file upload server as well
if "upload_dir" in config["configuration"]:
from upload import UploadPage
updir = replaceVariables(config['configuration']['upload_dir'], [config['properties']], sanitize)
uploadResource = UploadPage(updir)
web_resource.putChild("upload", uploadResource)
site = server.Site(web_resource)
reactor.listenTCP(port, site, interface=host)
reactor.run()
# =============================================================================
# Parse config file
# =============================================================================