def find_handlers( obj: logging.Logger, hname: str = "", htype: logging.Handler = None, traverse: bool = True, ) -> Dict[str, List[logging.Handler]]: """Remove the NullHandler from a logger if found. Notes: * will remove handler if hname supplied and handler obj name matches * will remove handler if htype supplied and handler obj type matches Args: obj: logger obj to search for handler in traverse: traverse the logger obj supplied up to the root logger hname: name of handler to search for htype: type of handler to find """ handlers = {} for handler in obj.handlers: match_name = hname and handler.name == hname match_type = htype and isinstance(handler, htype) if match_name or match_type: handlers[obj.name] = handlers.get(obj.name, []) if handler not in handlers[obj.name]: handlers[obj.name].append(handler) if obj.parent and traverse: found = find_handlers(obj=obj.parent, hname=hname, htype=htype, traverse=traverse) handlers.update(found) return handlers
def create_loggers(): folders = get_immediate_subdirectories("bots") for folder in folders: if not os.path.exists('bots/' + folder + '/logs/'): os.makedirs('bots/' + folder + '/logs/') LOG_FILENAME = 'bots/' + folder + '/logs/full_log.out' REC_FILENAME = 'bots/' + folder + '/logs/dm_log.out' formatter = logging.Formatter( '%(asctime)s - %(name)s - %(uid)s - %(levelname)s - %(message)s') # Set up a specific logger with our desired output level main_logger = logging.getLogger('Main logger') main_logger.setLevel(logging.DEBUG) state_logger = logging.getLogger('State info') state_logger.setLevel(logging.DEBUG) # Add the log message handler to the logger db_handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=10240 * 5, backupCount=5, encoding="UTF-8") nfo_handler = logging.handlers.RotatingFileHandler(REC_FILENAME, maxBytes=10240 * 5, backupCount=5, encoding="UTF-8") db_handler.setLevel(logging.DEBUG) nfo_handler.setLevel(logging.INFO) db_handler.setFormatter(formatter) nfo_handler.setFormatter(formatter) main_logger.addHandler(nfo_handler) state_logger.addHandler(db_handler) handlers.update({ folder.lower(): { "db_handler": db_handler, "nfo_handler": nfo_handler } }) loggers.update({ folder.lower(): { "main_logger": main_logger, "state_logger": state_logger } })
def find_handlers(obj, hname="", htype=None, traverse=True): """Remove the NullHandler from a logger if found. Notes: * will remove handler if hname supplied and handler obj name matches * will remove handler if htype supplied and handler obj type matches Args: obj (:obj:`logging.Logger`): logger obj to remove handler from hname (:obj:`str`, optional): default ``""`` - name of handler to find and remove htype (:class:`object`, optional): default ``None`` - type of handler to find and remove traverse (:obj:`bool`, optional): default ``True`` - * if ``True`` traverse the logger obj supplied up to the root logger to see if there are any matching attached handlers * if ``False`` only check the logger obj supplied for any matching attached handlers Returns: dict handler handler name->[handler objects] mapping of found handlers """ handlers = {} for handler in obj.handlers: match_name = hname and handler.name == hname match_type = htype and isinstance(handler, htype) if match_name or match_type: handlers[obj.name] = handlers.get(obj.name, []) if handler not in handlers[obj.name]: handlers[obj.name].append(handler) if obj.parent and traverse: found = find_handlers( obj=obj.parent, hname=hname, htype=htype, traverse=traverse ) handlers.update(found) return handlers
def find_handlers(obj, hname="", htype=None, traverse=True): """Find all handlers by traversing up the tree from obj.""" handlers = {} for handler in obj.handlers: match_name = hname and handler.name == hname match_type = htype and isinstance(handler, htype) if match_name or match_type: handlers[obj.name] = handlers.get(obj.name, []) if handler not in handlers[obj.name]: handlers[obj.name].append(handler) if obj.parent and traverse: found = find_handlers(obj=obj.parent, hname=hname, htype=htype, traverse=traverse) handlers.update(found) return handlers
def getpeercred(fd): """Return uid, gid and pid of calling application.""" import struct import socket try: SO_PEERCRED = getattr(socket, 'SO_PEERCRED', 17) creds = fd.getsockopt(socket.SOL_SOCKET, SO_PEERCRED, struct.calcsize('3i')) pid, uid, gid = struct.unpack('3i', creds) return uid, gid, pid except socket.error: return None, None, None handlers = {} handlers.update(common.get_handlers('config')) handlers.update(common.get_handlers('alias')) handlers.update(common.get_handlers('ether')) handlers.update(common.get_handlers('group')) handlers.update(common.get_handlers('host')) handlers.update(common.get_handlers('netgroup')) handlers.update(common.get_handlers('network')) handlers.update(common.get_handlers('passwd')) handlers.update(common.get_handlers('protocol')) handlers.update(common.get_handlers('rpc')) handlers.update(common.get_handlers('service')) handlers.update(common.get_handlers('shadow')) handlers.update(common.get_handlers('pam')) handlers.update(common.get_handlers('usermod'))
# add null handlers for all levels null = NullHandler() null.setLevel(logging.NOTSET) logger.addHandler(null) # assign a single level handler for each level handlers = { logging.DEBUG: SingleLevelStreamHandler(), logging.INFO: SingleLevelStreamHandler(), logging.WARNING: SingleLevelStreamHandler(), logging.ERROR: SingleLevelStreamHandler(), logging.CRITICAL: SingleLevelStreamHandler(), } if os.name == 'posix': handlers.update({ 1000: SysLogHandler('/dev/log'), }) def configure_syslog_handler(name, censored): if os.name != 'posix': return handlers[1000].name = name handlers[1000].censored = censored handlers[1000].applyFormat() def get_formatter(level): # default to DEBUG if the level is invalid if level not in handlers.keys(): level = logging.DEBUG # return the appropriate formatter if level == logging.DEBUG:
def getpeercred(fd): """Return uid, gid and pid of calling application.""" import struct import socket try: SO_PEERCRED = getattr(socket, "SO_PEERCRED", 17) creds = fd.getsockopt(socket.SOL_SOCKET, SO_PEERCRED, struct.calcsize("3i")) pid, uid, gid = struct.unpack("3i", creds) return uid, gid, pid except socket.error: return None, None, None handlers = {} handlers.update(common.get_handlers("config")) handlers.update(common.get_handlers("alias")) handlers.update(common.get_handlers("ether")) handlers.update(common.get_handlers("group")) handlers.update(common.get_handlers("host")) handlers.update(common.get_handlers("netgroup")) handlers.update(common.get_handlers("network")) handlers.update(common.get_handlers("passwd")) handlers.update(common.get_handlers("protocol")) handlers.update(common.get_handlers("rpc")) handlers.update(common.get_handlers("service")) handlers.update(common.get_handlers("shadow")) handlers.update(common.get_handlers("pam")) handlers.update(common.get_handlers("usermod"))