[docs]classSysLogHandlerWrapper(logging.handlers.SysLogHandler):""" Override the priority_map :class:`SysLogHandler`. .. warning:: This messages at DEBUG and INFO are therefore not stored by ASL, (ASL = Apple System Log) which in turn means they can't be printed by syslog after the fact. You can confirm it via :command:`syslog` or :command:`tail -f /var/log/system.log`. """priority_map={'DEBUG':'debug','INFO':'info','WARNING':'warning','ERROR':'error','CRITICAL':'critical',}
[docs]classJinaLogger:""" Build a logger for a context. :param context: The context identifier of the class, module or method. :param log_config: The configuration file for the logger. configuration to group logs by deployment. :return:: an executor object. """supported={'FileHandler','StreamHandler','SysLogHandler','RichHandler'}def__init__(self,context:str,name:Optional[str]=None,log_config:Optional[str]=None,quiet:bool=False,**kwargs,):ifnotlog_config:log_config=os.getenv('JINA_LOG_CONFIG',os.path.join(__resources_path__,'logging.default.yml'),)ifquietoros.getenv('JINA_LOG_CONFIG',None)=='QUIET':log_config=os.path.join(__resources_path__,'logging.quiet.yml')ifnotname:name=os.getenv('JINA_DEPLOYMENT_NAME',context)# Remove all handlers associated with the root logger object.forhandlerinlogging.root.handlers[:]:logging.root.removeHandler(handler)self.logger=logging.getLogger(context)self.logger.propagate=Falsecontext_vars={'name':name,'uptime':__uptime__,'context':context,}self.add_handlers(log_config,**context_vars)self.success=lambda*x:self.logger.log(LogVerbosity.SUCCESS,*x)self.debug=self.logger.debugself.warning=self.logger.warningself.critical=self.logger.criticalself.error=self.logger.errorself.info=self.logger.infoself._is_closed=Falseself.debug_enabled=self.logger.isEnabledFor(logging.DEBUG)@propertydefhandlers(self):""" Get the handlers of the logger. :return:: Handlers of logger. """returnself.logger.handlersdef__enter__(self):returnselfdef__exit__(self,exc_type,exc_val,exc_tb):self.close()
[docs]defclose(self):"""Close all the handlers."""ifnotself._is_closed:forhandlerinself.logger.handlers:handler.close()self._is_closed=True
[docs]defadd_handlers(self,config_path:Optional[str]=None,**kwargs):""" Add handlers from config file. :param config_path: Path of config file. :param kwargs: Extra parameters. """self.logger.handlers=[]withopen(config_path)asfp:config=JAML.load(fp)forhinconfig['handlers']:cfg=config['configs'].get(h,None)fmt=getattr(formatter,cfg.get('formatter','Formatter'))ifhnotinself.supportedornotcfg:raiseValueError(f'can not find configs for {h}, maybe it is not supported')handler=Noneifh=='StreamHandler':handler=logging.StreamHandler(sys.stdout)handler.setFormatter(fmt(cfg['format'].format_map(kwargs)))ifh=='RichHandler':kwargs_handler=copy.deepcopy(cfg)kwargs_handler.pop('format')handler=RichHandler(**kwargs_handler)handler.setFormatter(fmt(cfg['format'].format_map(kwargs)))elifh=='SysLogHandler'andnot__windows__:ifcfg['host']andcfg['port']:handler=SysLogHandlerWrapper(address=(cfg['host'],cfg['port']))else:# a UNIX socket is usedifplatform.system()=='Darwin':handler=SysLogHandlerWrapper(address='/var/run/syslog')else:handler=SysLogHandlerWrapper(address='/dev/log')ifhandler:handler.ident=cfg.get('ident','')handler.setFormatter(fmt(cfg['format'].format_map(kwargs)))try:handler._connect_unixsocket(handler.address)exceptOSError:handler=Nonepasselifh=='FileHandler':filename=cfg['output'].format_map(kwargs)if__windows__:# colons are not allowed in filenamesfilename=filename.replace(':','.')handler=logging.FileHandler(filename,delay=True)handler.setFormatter(fmt(cfg['format'].format_map(kwargs)))ifhandler:self.logger.addHandler(handler)verbose_level=LogVerbosity.from_string(config['level'])if'JINA_LOG_LEVEL'inos.environ:verbose_level=LogVerbosity.from_string(os.environ['JINA_LOG_LEVEL'])self.logger.setLevel(verbose_level.value)