當前位置: 首頁>>代碼示例>>Python>>正文


Python logging.handlers方法代碼示例

本文整理匯總了Python中logging.handlers方法的典型用法代碼示例。如果您正苦於以下問題:Python logging.handlers方法的具體用法?Python logging.handlers怎麽用?Python logging.handlers使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在logging的用法示例。


在下文中一共展示了logging.handlers方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _EventLogUpload

# 需要導入模塊: import logging [as 別名]
# 或者: from logging import handlers [as 別名]
def _EventLogUpload(self, source_log: Text):
    """Upload the log file contents to the local EventLog."""
    event_handler = logging.handlers.NTEventLogHandler('GlazierBuildLog')
    logger = logging.Logger('eventlogger')
    logger.addHandler(event_handler)
    logger.setLevel(logging.DEBUG)

    try:
      with open(source_log, 'r') as f:
        content = f.readlines()
        for line in content:
          logger.info(line)
    except IOError:
      raise LogCopyError(
          'Unable to open log file. It will not be imported into '
          'the Windows Event Log.') 
開發者ID:google,項目名稱:glazier,代碼行數:18,代碼來源:log_copy.py

示例2: _handle_existing_loggers

# 需要導入模塊: import logging [as 別名]
# 或者: from logging import handlers [as 別名]
def _handle_existing_loggers(existing, child_loggers, disable_existing):
    """
    When (re)configuring logging, handle loggers which were in the previous
    configuration but are not in the new configuration. There's no point
    deleting them as other threads may continue to hold references to them;
    and by disabling them, you stop them doing any logging.

    However, don't disable children of named loggers, as that's probably not
    what was intended by the user. Also, allow existing loggers to NOT be
    disabled if disable_existing is false.
    """
    root = logging.root
    for log in existing:
        logger = root.manager.loggerDict[log]
        if log in child_loggers:
            logger.level = logging.NOTSET
            logger.handlers = []
            logger.propagate = True
        else:
            logger.disabled = disable_existing 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:22,代碼來源:config.py

示例3: init_app

# 需要導入模塊: import logging [as 別名]
# 或者: from logging import handlers [as 別名]
def init_app(cls, app):
        Config.init_app(app)

        # email errors to the administrators
        import logging
        from logging.handlers import SMTPHandler
        credentials = None
        secure = None
        if getattr(cls, 'MAIL_USERNAME', None) is not None:
            credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD)
            if getattr(cls, 'MAIL_USE_TLS', None):
                secure = ()
        mail_handler = SMTPHandler(
            mailhost=(cls.MAIL_SERVER, cls.MAIL_PORT),
            fromaddr=cls.CIRCULATE_MAIL_SENDER,
            toaddrs=[cls.CIRCULATE_ADMIN],
            subject=cls.CIRCULATE_MAIL_SUBJECT_PREFIX + ' Application Error',
            credentials=credentials,
            secure=secure)
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler) 
開發者ID:CircleCI-Public,項目名稱:circleci-demo-python-flask,代碼行數:23,代碼來源:config.py

示例4: setupLogging

# 需要導入模塊: import logging [as 別名]
# 或者: from logging import handlers [as 別名]
def setupLogging(self):
        logger = logging.getLogger()
        formatter = logging.Formatter('%(asctime)s [%(levelname)-8s] %(message)s')
        path = userpath('logs', 'leaguedirector.log')
        handler = logging.handlers.RotatingFileHandler(path, backupCount=20)
        try:
            handler.doRollover()
        except Exception: pass
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        handler = logging.StreamHandler()
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        logger.setLevel(logging.INFO)
        logging.info('Started League Director (%s)', leaguedirector.__version__)
        qInstallMessageHandler(self.handleMessage) 
開發者ID:RiotGames,項目名稱:leaguedirector,代碼行數:18,代碼來源:app.py

示例5: setup_logger

# 需要導入模塊: import logging [as 別名]
# 或者: from logging import handlers [as 別名]
def setup_logger(name, level=logging.INFO, maxBytes=25000000, backupCount=5, format=SHORT_FORMAT):
        """ Set up a logging instance.

        @param name:        The log file name.
                            We recommend "$action_name$_modalert".
        @param level:       The logging level.
        @param maxBytes:    The maximum log file size before rollover.
        @param backupCount: The number of log files to retain.

        @return logger:     Returns an instance of logger
        """
        logfile = make_splunkhome_path(['var', 'log', 'splunk', name + '.log'])
        logger = logging.getLogger(name)
        logger.setLevel(level)
        logger.propagate = False  # Prevent the log messages from being duplicated in the python.log file

        # Prevent re-adding handlers to the logger object, which can cause duplicate log lines.
        handler_exists = any([True for h in logger.handlers if h.baseFilename == logfile])
        if not handler_exists:
            file_handler = logging.handlers.RotatingFileHandler(logfile, maxBytes=maxBytes, backupCount=backupCount)
            formatter = logging.Formatter(format)
            file_handler.setFormatter(formatter)
            logger.addHandler(file_handler)

        return logger 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:27,代碼來源:cim_actions.py

示例6: logger

# 需要導入模塊: import logging [as 別名]
# 或者: from logging import handlers [as 別名]
def logger():
    logger = logging.getLogger('testlog')

    logHandler = TimedRotatingFileHandler(filename="logfile", when="midnight")
    logFormatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
    logHandler.setFormatter(logFormatter)



    if not logger.handlers:
        streamhandler = logging.StreamHandler()
        streamhandler.setLevel(logging.ERROR)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')
        streamhandler.setFormatter(formatter)

        logger.addHandler(streamhandler)
        logger.addHandler(logHandler)


    # logger.error(message)
    return logger 
開發者ID:makelove,項目名稱:Python_Master_Courses,代碼行數:23,代碼來源:問題2.py

示例7: colorize_status

# 需要導入模塊: import logging [as 別名]
# 或者: from logging import handlers [as 別名]
def colorize_status(text: Optional[Union[str, int]], status: Optional[Union[str, int, bool]] = False) -> str:
        if status is False:
            status = text
        status_code = str(status) if status else None
        if status_code and not logging.getLogger('transport.http').handlers:
            output_text = str(text) if text else ''
            color = None

            if status_code == '101':
                color = colorama.Fore.CYAN
            elif status_code[0] == '2':
                color = colorama.Fore.GREEN
            elif status_code[0] == '3' or status_code == '499':
                color = colorama.Fore.YELLOW
            elif status_code[0] == '4':
                color = colorama.Fore.RED
            elif status_code[0] == '5':
                color = colorama.Fore.WHITE + colorama.Back.RED

            if color:
                return '{}{}{}'.format(color, output_text, colorama.Style.RESET_ALL)
            return output_text

        return str(text) if text else '' 
開發者ID:kalaspuff,項目名稱:tomodachi,代碼行數:26,代碼來源:http.py

示例8: common_logger_config

# 需要導入模塊: import logging [as 別名]
# 或者: from logging import handlers [as 別名]
def common_logger_config(self, logger, config, incremental=False):
        """
        Perform configuration which is common to root and non-root loggers.
        """
        level = config.get('level', None)
        if level is not None:
            logger.setLevel(_checkLevel(level))
        if not incremental:
            # Remove any existing handlers
            for h in logger.handlers[:]:
                logger.removeHandler(h)
            handlers = config.get('handlers', None)
            if handlers:
                self.add_handlers(logger, handlers)
            filters = config.get('filters', None)
            if filters:
                self.add_filters(logger, filters) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:19,代碼來源:dictconfig.py

示例9: init_app

# 需要導入模塊: import logging [as 別名]
# 或者: from logging import handlers [as 別名]
def init_app(cls, app):
        Config.init_app(app)

        # 把錯誤發送管理員
        import logging
        from logging.handlers import SMTPHandler
        credentials = None
        secure = None
        if getattr(cls, 'MAIL_USERNAME', None) is not None:
            credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD)
            if getattr(cls, 'MAIL_USE_TLS', None):
                secure = ()
        mail_handler = SMTPHandler(
            mailhost=(cls.MAIL_SERVER, cls.MAIL_PORT),
            fromaddr=cls.MAIL_SENDER,
            toaddrs=[cls.ADMINMAIL],
            subject=cls.MAIL_SUBJECT_PREFIX + ' Application Error',
            credentials=credentials,
            secure=secure)
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler) 
開發者ID:Blackyukun,項目名稱:Simpleblog,代碼行數:23,代碼來源:config.py

示例10: configure

# 需要導入模塊: import logging [as 別名]
# 或者: from logging import handlers [as 別名]
def configure(self, args):
        """ Configure the loggers with the appropriate log level etc.

        :param args: The arguments from the command line
        :type args: list
        """
        log_level = self._determine_log_level(args)
        log_level_config = self.console_log_configs[log_level]
        root_logger = logging.getLogger()
        cli_logger = logging.getLogger(CLI_LOGGER_NAME)
        # Set the levels of the loggers to lowest level.
        # Handlers can override by choosing a higher level.
        root_logger.setLevel(logging.DEBUG)
        cli_logger.setLevel(logging.DEBUG)
        cli_logger.propagate = False
        if root_logger.handlers and cli_logger.handlers:
            # loggers already configured
            return
        self._init_console_handlers(root_logger, cli_logger, log_level_config)
        if self.file_log_enabled:
            self._init_logfile_handlers(root_logger, cli_logger)
            get_logger(__name__).debug("File logging enabled - writing logs to '%s'.", self.log_dir) 
開發者ID:microsoft,項目名稱:knack,代碼行數:24,代碼來源:log.py

示例11: add_handler

# 需要導入模塊: import logging [as 別名]
# 或者: from logging import handlers [as 別名]
def add_handler(cls, level, fmt, colorful, **kwargs):
    """Add a configured handlers to the global logger."""
    global g_logger

    if isinstance(level, str):
        level = getattr(logging, level.upper(), logging.INFO)

    handler = cls(**kwargs)
    handler.setLevel(level)

    if colorful:
        formatter = ColoredFormatter(fmt)
    else:
        formatter = logging.Formatter(fmt)

    handler.setFormatter(formatter)
    g_logger.addHandler(handler)

    return handler 
開發者ID:lucasxlu,項目名稱:LagouJob,代碼行數:21,代碼來源:log.py

示例12: init_app

# 需要導入模塊: import logging [as 別名]
# 或者: from logging import handlers [as 別名]
def init_app(cls, app):
        Config.init_app(app)

        import logging
        from logging.handlers import SMTPHandler
        credentials = None
        secure = None
        if getattr(cls, 'MAIL_USERNAME', None) is not None:
            credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD)
            if getattr(cls, 'MAIL_USE_TLS', None):
                secure = ()
        mail_handler = SMTPHandler(
            mailhost=(cls.MAIL_SERVER, cls.MAIL_PORT),
            fromaddr=cls.FLASHCARD_MAIL_SENDER,
            toaddrs=[cls.FLASHCARD_ADMIN],
            subject=cls.FLASHCARD_MAIL_SUBJECT_PREFIX + 'Application Error',
            credentials=credentials,
            secure=secure)
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler) 
開發者ID:KevDi,項目名稱:Flashcards,代碼行數:22,代碼來源:config.py

示例13: get_logger

# 需要導入模塊: import logging [as 別名]
# 或者: from logging import handlers [as 別名]
def get_logger(cls, name, level='INFO', filepath=None, fmt=None):
        '''
            Return a new logger or an existing one, if any.

        :param cls     : The class as implicit first argument.
        :param name    : Return a logger with the specified name.
        :param filepath: Path of the file, where logs will be saved. If it is not set,
                         redirects the log stream to `sys.stdout`.
        :param fmt     : A format string for the message as a whole, as well as a format
                         string for the date/time portion of the message.
                         Default: '%(asctime)s %(levelname)-8s %(name)-34s %(message)s'
        :rtype         : :class:`logging.Logger`
        '''
        logger = logging.getLogger(name)
        # .............................if logger already exists, return it
        if logger.handlers: return logger

        if filepath:
            # .........................rotate log file (1 rotation per 512KB
            handler  = RotatingFileHandler(filepath, maxBytes=524288, backupCount=8)
        else:
            handler  = logging.StreamHandler(sys.stdout)

        fmt = fmt or '%(asctime)s %(levelname)-8s %(name)-34s %(message)s'
        handler.setFormatter(logging.Formatter(fmt))

        try:
            logger.setLevel(getattr(logging, level.upper() if level else 'INFO'))
        except: logger.setLevel(logging.INFO)

        logger.addHandler(handler)
        return logger 
開發者ID:apache,項目名稱:incubator-spot,代碼行數:34,代碼來源:utils.py

示例14: handler_datapath

# 需要導入模塊: import logging [as 別名]
# 或者: from logging import handlers [as 別名]
def handler_datapath(self, ev):
        ryudp = ev.dp
        dp = self.dps[ryudp.id]
        # Set up a thread to poll for port stats
        # TODO: set up threads to poll for other stats as well
        # TODO: allow the different things to be polled for to be
        # configurable
        dp.running = True
        if dp.dp_id not in self.pollers:
            self.pollers[dp.dp_id] = {}
            self.handlers[dp.dp_id] = {}

        if dp.influxdb_stats:
            port_state_handler = GaugePortStateInfluxDBLogger(
                dp, ryudp, self.logname)
        else:
            port_state_handler = GaugePortStateLogger(
                dp, ryudp, self.logname)
        self.handlers[dp.dp_id]['port_state'] = port_state_handler

        if dp.monitor_ports:
            if dp.influxdb_stats:
                port_stats_poller = GaugePortStatsInfluxDBPoller(
                   dp, ryudp, self.logname)
            else:
                port_stats_poller = GaugePortStatsPoller(
                    dp, ryudp, self.logname)
            self.pollers[dp.dp_id]['port_stats'] = port_stats_poller
            port_stats_poller.start()

        if dp.monitor_flow_table:
            if dp.influxdb_stats:
                flow_table_poller = GaugeFlowTableInfluxDBPoller(
                    dp, ryudp, self.logname)
            else:
                flow_table_poller = GaugeFlowTablePoller(
                    dp, ryudp, self.logname)
            self.pollers[dp.dp_id]['flow_table'] = flow_table_poller
            flow_table_poller.start() 
開發者ID:sdn-ixp,項目名稱:iSDX,代碼行數:41,代碼來源:gauge.py

示例15: port_status_handler

# 需要導入模塊: import logging [as 別名]
# 或者: from logging import handlers [as 別名]
def port_status_handler(self, ev):
        rcv_time = time.time()
        dp = self.dps[ev.msg.datapath.id]
        self.handlers[dp.dp_id]['port_state'].update(rcv_time, ev.msg) 
開發者ID:sdn-ixp,項目名稱:iSDX,代碼行數:6,代碼來源:gauge.py


注:本文中的logging.handlers方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。