Edit File by line
/home/barbar84/www/wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../usr/lib64/python3..../logging
File: config.py
incremental = config.pop('incremental', False)
[500] Fix | Delete
EMPTY_DICT = {}
[501] Fix | Delete
logging._acquireLock()
[502] Fix | Delete
try:
[503] Fix | Delete
if incremental:
[504] Fix | Delete
handlers = config.get('handlers', EMPTY_DICT)
[505] Fix | Delete
for name in handlers:
[506] Fix | Delete
if name not in logging._handlers:
[507] Fix | Delete
raise ValueError('No handler found with '
[508] Fix | Delete
'name %r' % name)
[509] Fix | Delete
else:
[510] Fix | Delete
try:
[511] Fix | Delete
handler = logging._handlers[name]
[512] Fix | Delete
handler_config = handlers[name]
[513] Fix | Delete
level = handler_config.get('level', None)
[514] Fix | Delete
if level:
[515] Fix | Delete
handler.setLevel(logging._checkLevel(level))
[516] Fix | Delete
except Exception as e:
[517] Fix | Delete
raise ValueError('Unable to configure handler '
[518] Fix | Delete
'%r: %s' % (name, e))
[519] Fix | Delete
loggers = config.get('loggers', EMPTY_DICT)
[520] Fix | Delete
for name in loggers:
[521] Fix | Delete
try:
[522] Fix | Delete
self.configure_logger(name, loggers[name], True)
[523] Fix | Delete
except Exception as e:
[524] Fix | Delete
raise ValueError('Unable to configure logger '
[525] Fix | Delete
'%r: %s' % (name, e))
[526] Fix | Delete
root = config.get('root', None)
[527] Fix | Delete
if root:
[528] Fix | Delete
try:
[529] Fix | Delete
self.configure_root(root, True)
[530] Fix | Delete
except Exception as e:
[531] Fix | Delete
raise ValueError('Unable to configure root '
[532] Fix | Delete
'logger: %s' % e)
[533] Fix | Delete
else:
[534] Fix | Delete
disable_existing = config.pop('disable_existing_loggers', True)
[535] Fix | Delete
[536] Fix | Delete
_clearExistingHandlers()
[537] Fix | Delete
[538] Fix | Delete
# Do formatters first - they don't refer to anything else
[539] Fix | Delete
formatters = config.get('formatters', EMPTY_DICT)
[540] Fix | Delete
for name in formatters:
[541] Fix | Delete
try:
[542] Fix | Delete
formatters[name] = self.configure_formatter(
[543] Fix | Delete
formatters[name])
[544] Fix | Delete
except Exception as e:
[545] Fix | Delete
raise ValueError('Unable to configure '
[546] Fix | Delete
'formatter %r: %s' % (name, e))
[547] Fix | Delete
# Next, do filters - they don't refer to anything else, either
[548] Fix | Delete
filters = config.get('filters', EMPTY_DICT)
[549] Fix | Delete
for name in filters:
[550] Fix | Delete
try:
[551] Fix | Delete
filters[name] = self.configure_filter(filters[name])
[552] Fix | Delete
except Exception as e:
[553] Fix | Delete
raise ValueError('Unable to configure '
[554] Fix | Delete
'filter %r: %s' % (name, e))
[555] Fix | Delete
[556] Fix | Delete
# Next, do handlers - they refer to formatters and filters
[557] Fix | Delete
# As handlers can refer to other handlers, sort the keys
[558] Fix | Delete
# to allow a deterministic order of configuration
[559] Fix | Delete
handlers = config.get('handlers', EMPTY_DICT)
[560] Fix | Delete
deferred = []
[561] Fix | Delete
for name in sorted(handlers):
[562] Fix | Delete
try:
[563] Fix | Delete
handler = self.configure_handler(handlers[name])
[564] Fix | Delete
handler.name = name
[565] Fix | Delete
handlers[name] = handler
[566] Fix | Delete
except Exception as e:
[567] Fix | Delete
if 'target not configured yet' in str(e):
[568] Fix | Delete
deferred.append(name)
[569] Fix | Delete
else:
[570] Fix | Delete
raise ValueError('Unable to configure handler '
[571] Fix | Delete
'%r: %s' % (name, e))
[572] Fix | Delete
[573] Fix | Delete
# Now do any that were deferred
[574] Fix | Delete
for name in deferred:
[575] Fix | Delete
try:
[576] Fix | Delete
handler = self.configure_handler(handlers[name])
[577] Fix | Delete
handler.name = name
[578] Fix | Delete
handlers[name] = handler
[579] Fix | Delete
except Exception as e:
[580] Fix | Delete
raise ValueError('Unable to configure handler '
[581] Fix | Delete
'%r: %s' % (name, e))
[582] Fix | Delete
[583] Fix | Delete
# Next, do loggers - they refer to handlers and filters
[584] Fix | Delete
[585] Fix | Delete
#we don't want to lose the existing loggers,
[586] Fix | Delete
#since other threads may have pointers to them.
[587] Fix | Delete
#existing is set to contain all existing loggers,
[588] Fix | Delete
#and as we go through the new configuration we
[589] Fix | Delete
#remove any which are configured. At the end,
[590] Fix | Delete
#what's left in existing is the set of loggers
[591] Fix | Delete
#which were in the previous configuration but
[592] Fix | Delete
#which are not in the new configuration.
[593] Fix | Delete
root = logging.root
[594] Fix | Delete
existing = list(root.manager.loggerDict.keys())
[595] Fix | Delete
#The list needs to be sorted so that we can
[596] Fix | Delete
#avoid disabling child loggers of explicitly
[597] Fix | Delete
#named loggers. With a sorted list it is easier
[598] Fix | Delete
#to find the child loggers.
[599] Fix | Delete
existing.sort()
[600] Fix | Delete
#We'll keep the list of existing loggers
[601] Fix | Delete
#which are children of named loggers here...
[602] Fix | Delete
child_loggers = []
[603] Fix | Delete
#now set up the new ones...
[604] Fix | Delete
loggers = config.get('loggers', EMPTY_DICT)
[605] Fix | Delete
for name in loggers:
[606] Fix | Delete
if name in existing:
[607] Fix | Delete
i = existing.index(name) + 1 # look after name
[608] Fix | Delete
prefixed = name + "."
[609] Fix | Delete
pflen = len(prefixed)
[610] Fix | Delete
num_existing = len(existing)
[611] Fix | Delete
while i < num_existing:
[612] Fix | Delete
if existing[i][:pflen] == prefixed:
[613] Fix | Delete
child_loggers.append(existing[i])
[614] Fix | Delete
i += 1
[615] Fix | Delete
existing.remove(name)
[616] Fix | Delete
try:
[617] Fix | Delete
self.configure_logger(name, loggers[name])
[618] Fix | Delete
except Exception as e:
[619] Fix | Delete
raise ValueError('Unable to configure logger '
[620] Fix | Delete
'%r: %s' % (name, e))
[621] Fix | Delete
[622] Fix | Delete
#Disable any old loggers. There's no point deleting
[623] Fix | Delete
#them as other threads may continue to hold references
[624] Fix | Delete
#and by disabling them, you stop them doing any logging.
[625] Fix | Delete
#However, don't disable children of named loggers, as that's
[626] Fix | Delete
#probably not what was intended by the user.
[627] Fix | Delete
#for log in existing:
[628] Fix | Delete
# logger = root.manager.loggerDict[log]
[629] Fix | Delete
# if log in child_loggers:
[630] Fix | Delete
# logger.level = logging.NOTSET
[631] Fix | Delete
# logger.handlers = []
[632] Fix | Delete
# logger.propagate = True
[633] Fix | Delete
# elif disable_existing:
[634] Fix | Delete
# logger.disabled = True
[635] Fix | Delete
_handle_existing_loggers(existing, child_loggers,
[636] Fix | Delete
disable_existing)
[637] Fix | Delete
[638] Fix | Delete
# And finally, do the root logger
[639] Fix | Delete
root = config.get('root', None)
[640] Fix | Delete
if root:
[641] Fix | Delete
try:
[642] Fix | Delete
self.configure_root(root)
[643] Fix | Delete
except Exception as e:
[644] Fix | Delete
raise ValueError('Unable to configure root '
[645] Fix | Delete
'logger: %s' % e)
[646] Fix | Delete
finally:
[647] Fix | Delete
logging._releaseLock()
[648] Fix | Delete
[649] Fix | Delete
def configure_formatter(self, config):
[650] Fix | Delete
"""Configure a formatter from a dictionary."""
[651] Fix | Delete
if '()' in config:
[652] Fix | Delete
factory = config['()'] # for use in exception handler
[653] Fix | Delete
try:
[654] Fix | Delete
result = self.configure_custom(config)
[655] Fix | Delete
except TypeError as te:
[656] Fix | Delete
if "'format'" not in str(te):
[657] Fix | Delete
raise
[658] Fix | Delete
#Name of parameter changed from fmt to format.
[659] Fix | Delete
#Retry with old name.
[660] Fix | Delete
#This is so that code can be used with older Python versions
[661] Fix | Delete
#(e.g. by Django)
[662] Fix | Delete
config['fmt'] = config.pop('format')
[663] Fix | Delete
config['()'] = factory
[664] Fix | Delete
result = self.configure_custom(config)
[665] Fix | Delete
else:
[666] Fix | Delete
fmt = config.get('format', None)
[667] Fix | Delete
dfmt = config.get('datefmt', None)
[668] Fix | Delete
style = config.get('style', '%')
[669] Fix | Delete
cname = config.get('class', None)
[670] Fix | Delete
if not cname:
[671] Fix | Delete
c = logging.Formatter
[672] Fix | Delete
else:
[673] Fix | Delete
c = _resolve(cname)
[674] Fix | Delete
result = c(fmt, dfmt, style)
[675] Fix | Delete
return result
[676] Fix | Delete
[677] Fix | Delete
def configure_filter(self, config):
[678] Fix | Delete
"""Configure a filter from a dictionary."""
[679] Fix | Delete
if '()' in config:
[680] Fix | Delete
result = self.configure_custom(config)
[681] Fix | Delete
else:
[682] Fix | Delete
name = config.get('name', '')
[683] Fix | Delete
result = logging.Filter(name)
[684] Fix | Delete
return result
[685] Fix | Delete
[686] Fix | Delete
def add_filters(self, filterer, filters):
[687] Fix | Delete
"""Add filters to a filterer from a list of names."""
[688] Fix | Delete
for f in filters:
[689] Fix | Delete
try:
[690] Fix | Delete
filterer.addFilter(self.config['filters'][f])
[691] Fix | Delete
except Exception as e:
[692] Fix | Delete
raise ValueError('Unable to add filter %r: %s' % (f, e))
[693] Fix | Delete
[694] Fix | Delete
def configure_handler(self, config):
[695] Fix | Delete
"""Configure a handler from a dictionary."""
[696] Fix | Delete
config_copy = dict(config) # for restoring in case of error
[697] Fix | Delete
formatter = config.pop('formatter', None)
[698] Fix | Delete
if formatter:
[699] Fix | Delete
try:
[700] Fix | Delete
formatter = self.config['formatters'][formatter]
[701] Fix | Delete
except Exception as e:
[702] Fix | Delete
raise ValueError('Unable to set formatter '
[703] Fix | Delete
'%r: %s' % (formatter, e))
[704] Fix | Delete
level = config.pop('level', None)
[705] Fix | Delete
filters = config.pop('filters', None)
[706] Fix | Delete
if '()' in config:
[707] Fix | Delete
c = config.pop('()')
[708] Fix | Delete
if not callable(c):
[709] Fix | Delete
c = self.resolve(c)
[710] Fix | Delete
factory = c
[711] Fix | Delete
else:
[712] Fix | Delete
cname = config.pop('class')
[713] Fix | Delete
klass = self.resolve(cname)
[714] Fix | Delete
#Special case for handler which refers to another handler
[715] Fix | Delete
if issubclass(klass, logging.handlers.MemoryHandler) and\
[716] Fix | Delete
'target' in config:
[717] Fix | Delete
try:
[718] Fix | Delete
th = self.config['handlers'][config['target']]
[719] Fix | Delete
if not isinstance(th, logging.Handler):
[720] Fix | Delete
config.update(config_copy) # restore for deferred cfg
[721] Fix | Delete
raise TypeError('target not configured yet')
[722] Fix | Delete
config['target'] = th
[723] Fix | Delete
except Exception as e:
[724] Fix | Delete
raise ValueError('Unable to set target handler '
[725] Fix | Delete
'%r: %s' % (config['target'], e))
[726] Fix | Delete
elif issubclass(klass, logging.handlers.SMTPHandler) and\
[727] Fix | Delete
'mailhost' in config:
[728] Fix | Delete
config['mailhost'] = self.as_tuple(config['mailhost'])
[729] Fix | Delete
elif issubclass(klass, logging.handlers.SysLogHandler) and\
[730] Fix | Delete
'address' in config:
[731] Fix | Delete
config['address'] = self.as_tuple(config['address'])
[732] Fix | Delete
factory = klass
[733] Fix | Delete
props = config.pop('.', None)
[734] Fix | Delete
kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
[735] Fix | Delete
try:
[736] Fix | Delete
result = factory(**kwargs)
[737] Fix | Delete
except TypeError as te:
[738] Fix | Delete
if "'stream'" not in str(te):
[739] Fix | Delete
raise
[740] Fix | Delete
#The argument name changed from strm to stream
[741] Fix | Delete
#Retry with old name.
[742] Fix | Delete
#This is so that code can be used with older Python versions
[743] Fix | Delete
#(e.g. by Django)
[744] Fix | Delete
kwargs['strm'] = kwargs.pop('stream')
[745] Fix | Delete
result = factory(**kwargs)
[746] Fix | Delete
if formatter:
[747] Fix | Delete
result.setFormatter(formatter)
[748] Fix | Delete
if level is not None:
[749] Fix | Delete
result.setLevel(logging._checkLevel(level))
[750] Fix | Delete
if filters:
[751] Fix | Delete
self.add_filters(result, filters)
[752] Fix | Delete
if props:
[753] Fix | Delete
for name, value in props.items():
[754] Fix | Delete
setattr(result, name, value)
[755] Fix | Delete
return result
[756] Fix | Delete
[757] Fix | Delete
def add_handlers(self, logger, handlers):
[758] Fix | Delete
"""Add handlers to a logger from a list of names."""
[759] Fix | Delete
for h in handlers:
[760] Fix | Delete
try:
[761] Fix | Delete
logger.addHandler(self.config['handlers'][h])
[762] Fix | Delete
except Exception as e:
[763] Fix | Delete
raise ValueError('Unable to add handler %r: %s' % (h, e))
[764] Fix | Delete
[765] Fix | Delete
def common_logger_config(self, logger, config, incremental=False):
[766] Fix | Delete
"""
[767] Fix | Delete
Perform configuration which is common to root and non-root loggers.
[768] Fix | Delete
"""
[769] Fix | Delete
level = config.get('level', None)
[770] Fix | Delete
if level is not None:
[771] Fix | Delete
logger.setLevel(logging._checkLevel(level))
[772] Fix | Delete
if not incremental:
[773] Fix | Delete
#Remove any existing handlers
[774] Fix | Delete
for h in logger.handlers[:]:
[775] Fix | Delete
logger.removeHandler(h)
[776] Fix | Delete
handlers = config.get('handlers', None)
[777] Fix | Delete
if handlers:
[778] Fix | Delete
self.add_handlers(logger, handlers)
[779] Fix | Delete
filters = config.get('filters', None)
[780] Fix | Delete
if filters:
[781] Fix | Delete
self.add_filters(logger, filters)
[782] Fix | Delete
[783] Fix | Delete
def configure_logger(self, name, config, incremental=False):
[784] Fix | Delete
"""Configure a non-root logger from a dictionary."""
[785] Fix | Delete
logger = logging.getLogger(name)
[786] Fix | Delete
self.common_logger_config(logger, config, incremental)
[787] Fix | Delete
propagate = config.get('propagate', None)
[788] Fix | Delete
if propagate is not None:
[789] Fix | Delete
logger.propagate = propagate
[790] Fix | Delete
[791] Fix | Delete
def configure_root(self, config, incremental=False):
[792] Fix | Delete
"""Configure a root logger from a dictionary."""
[793] Fix | Delete
root = logging.getLogger()
[794] Fix | Delete
self.common_logger_config(root, config, incremental)
[795] Fix | Delete
[796] Fix | Delete
dictConfigClass = DictConfigurator
[797] Fix | Delete
[798] Fix | Delete
def dictConfig(config):
[799] Fix | Delete
"""Configure logging using a dictionary."""
[800] Fix | Delete
dictConfigClass(config).configure()
[801] Fix | Delete
[802] Fix | Delete
[803] Fix | Delete
def listen(port=DEFAULT_LOGGING_CONFIG_PORT, verify=None):
[804] Fix | Delete
"""
[805] Fix | Delete
Start up a socket server on the specified port, and listen for new
[806] Fix | Delete
configurations.
[807] Fix | Delete
[808] Fix | Delete
These will be sent as a file suitable for processing by fileConfig().
[809] Fix | Delete
Returns a Thread object on which you can call start() to start the server,
[810] Fix | Delete
and which you can join() when appropriate. To stop the server, call
[811] Fix | Delete
stopListening().
[812] Fix | Delete
[813] Fix | Delete
Use the ``verify`` argument to verify any bytes received across the wire
[814] Fix | Delete
from a client. If specified, it should be a callable which receives a
[815] Fix | Delete
single argument - the bytes of configuration data received across the
[816] Fix | Delete
network - and it should return either ``None``, to indicate that the
[817] Fix | Delete
passed in bytes could not be verified and should be discarded, or a
[818] Fix | Delete
byte string which is then passed to the configuration machinery as
[819] Fix | Delete
normal. Note that you can return transformed bytes, e.g. by decrypting
[820] Fix | Delete
the bytes passed in.
[821] Fix | Delete
"""
[822] Fix | Delete
if not thread: #pragma: no cover
[823] Fix | Delete
raise NotImplementedError("listen() needs threading to work")
[824] Fix | Delete
[825] Fix | Delete
class ConfigStreamHandler(StreamRequestHandler):
[826] Fix | Delete
"""
[827] Fix | Delete
Handler for a logging configuration request.
[828] Fix | Delete
[829] Fix | Delete
It expects a completely new logging configuration and uses fileConfig
[830] Fix | Delete
to install it.
[831] Fix | Delete
"""
[832] Fix | Delete
def handle(self):
[833] Fix | Delete
"""
[834] Fix | Delete
Handle a request.
[835] Fix | Delete
[836] Fix | Delete
Each request is expected to be a 4-byte length, packed using
[837] Fix | Delete
struct.pack(">L", n), followed by the config file.
[838] Fix | Delete
Uses fileConfig() to do the grunt work.
[839] Fix | Delete
"""
[840] Fix | Delete
try:
[841] Fix | Delete
conn = self.connection
[842] Fix | Delete
chunk = conn.recv(4)
[843] Fix | Delete
if len(chunk) == 4:
[844] Fix | Delete
slen = struct.unpack(">L", chunk)[0]
[845] Fix | Delete
chunk = self.connection.recv(slen)
[846] Fix | Delete
while len(chunk) < slen:
[847] Fix | Delete
chunk = chunk + conn.recv(slen - len(chunk))
[848] Fix | Delete
if self.server.verify is not None:
[849] Fix | Delete
chunk = self.server.verify(chunk)
[850] Fix | Delete
if chunk is not None: # verified, can process
[851] Fix | Delete
chunk = chunk.decode("utf-8")
[852] Fix | Delete
try:
[853] Fix | Delete
import json
[854] Fix | Delete
d =json.loads(chunk)
[855] Fix | Delete
assert isinstance(d, dict)
[856] Fix | Delete
dictConfig(d)
[857] Fix | Delete
except Exception:
[858] Fix | Delete
#Apply new configuration.
[859] Fix | Delete
[860] Fix | Delete
file = io.StringIO(chunk)
[861] Fix | Delete
try:
[862] Fix | Delete
fileConfig(file)
[863] Fix | Delete
except Exception:
[864] Fix | Delete
traceback.print_exc()
[865] Fix | Delete
if self.server.ready:
[866] Fix | Delete
self.server.ready.set()
[867] Fix | Delete
except OSError as e:
[868] Fix | Delete
if e.errno != RESET_ERROR:
[869] Fix | Delete
raise
[870] Fix | Delete
[871] Fix | Delete
class ConfigSocketReceiver(ThreadingTCPServer):
[872] Fix | Delete
"""
[873] Fix | Delete
A simple TCP socket-based logging config receiver.
[874] Fix | Delete
"""
[875] Fix | Delete
[876] Fix | Delete
allow_reuse_address = 1
[877] Fix | Delete
[878] Fix | Delete
def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT,
[879] Fix | Delete
handler=None, ready=None, verify=None):
[880] Fix | Delete
ThreadingTCPServer.__init__(self, (host, port), handler)
[881] Fix | Delete
logging._acquireLock()
[882] Fix | Delete
self.abort = 0
[883] Fix | Delete
logging._releaseLock()
[884] Fix | Delete
self.timeout = 1
[885] Fix | Delete
self.ready = ready
[886] Fix | Delete
self.verify = verify
[887] Fix | Delete
[888] Fix | Delete
def serve_until_stopped(self):
[889] Fix | Delete
import select
[890] Fix | Delete
abort = 0
[891] Fix | Delete
while not abort:
[892] Fix | Delete
rd, wr, ex = select.select([self.socket.fileno()],
[893] Fix | Delete
[], [],
[894] Fix | Delete
self.timeout)
[895] Fix | Delete
if rd:
[896] Fix | Delete
self.handle_request()
[897] Fix | Delete
logging._acquireLock()
[898] Fix | Delete
abort = self.abort
[899] Fix | Delete
logging._releaseLock()
[900] Fix | Delete
self.socket.close()
[901] Fix | Delete
[902] Fix | Delete
class Server(threading.Thread):
[903] Fix | Delete
[904] Fix | Delete
def __init__(self, rcvr, hdlr, port, verify):
[905] Fix | Delete
super(Server, self).__init__()
[906] Fix | Delete
self.rcvr = rcvr
[907] Fix | Delete
self.hdlr = hdlr
[908] Fix | Delete
self.port = port
[909] Fix | Delete
self.verify = verify
[910] Fix | Delete
self.ready = threading.Event()
[911] Fix | Delete
[912] Fix | Delete
def run(self):
[913] Fix | Delete
server = self.rcvr(port=self.port, handler=self.hdlr,
[914] Fix | Delete
ready=self.ready,
[915] Fix | Delete
verify=self.verify)
[916] Fix | Delete
if self.port == 0:
[917] Fix | Delete
self.port = server.server_address[1]
[918] Fix | Delete
self.ready.set()
[919] Fix | Delete
global _listener
[920] Fix | Delete
logging._acquireLock()
[921] Fix | Delete
_listener = server
[922] Fix | Delete
logging._releaseLock()
[923] Fix | Delete
server.serve_until_stopped()
[924] Fix | Delete
[925] Fix | Delete
return Server(ConfigSocketReceiver, ConfigStreamHandler, port, verify)
[926] Fix | Delete
[927] Fix | Delete
def stopListening():
[928] Fix | Delete
"""
[929] Fix | Delete
Stop the listening server which was created with a call to listen().
[930] Fix | Delete
"""
[931] Fix | Delete
global _listener
[932] Fix | Delete
logging._acquireLock()
[933] Fix | Delete
try:
[934] Fix | Delete
if _listener:
[935] Fix | Delete
_listener.abort = 1
[936] Fix | Delete
_listener = None
[937] Fix | Delete
finally:
[938] Fix | Delete
logging._releaseLock()
[939] Fix | Delete
[940] Fix | Delete
12
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function