Python logging.handlers() Examples

The following are 30 code examples for showing how to use logging.handlers(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module logging , or try the search function .

Example 1
Project: glazier   Author: google   File: log_copy.py    License: Apache License 2.0 6 votes vote down vote up
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.') 
Example 2
Project: jawfish   Author: war-and-code   File: config.py    License: MIT License 6 votes vote down vote up
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 
Example 3
Project: circleci-demo-python-flask   Author: CircleCI-Public   File: config.py    License: MIT License 6 votes vote down vote up
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) 
Example 4
Project: leaguedirector   Author: RiotGames   File: app.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 5
Project: misp42splunk   Author: remg427   File: cim_actions.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
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 
Example 6
Project: Python_Master_Courses   Author: makelove   File: 问题2.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 7
Project: tomodachi   Author: kalaspuff   File: http.py    License: MIT License 6 votes vote down vote up
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 '' 
Example 8
Project: recruit   Author: Frank-qlu   File: dictconfig.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 9
Project: Simpleblog   Author: Blackyukun   File: config.py    License: MIT License 6 votes vote down vote up
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) 
Example 10
Project: knack   Author: microsoft   File: log.py    License: MIT License 6 votes vote down vote up
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) 
Example 11
Project: jbox   Author: jpush   File: dictconfig.py    License: MIT License 6 votes vote down vote up
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) 
Example 12
Project: LagouJob   Author: lucasxlu   File: log.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 13
Project: Flashcards   Author: KevDi   File: config.py    License: MIT License 6 votes vote down vote up
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) 
Example 14
Project: incubator-spot   Author: apache   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
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 
Example 15
Project: iSDX   Author: sdn-ixp   File: gauge.py    License: Apache License 2.0 5 votes vote down vote up
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() 
Example 16
Project: iSDX   Author: sdn-ixp   File: gauge.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 17
Project: multibootusb   Author: mbusb   File: osdriver.py    License: GNU General Public License v2.0 5 votes vote down vote up
def initialize():
    logging.root.setLevel(logging.DEBUG)
    fmt = '%(asctime)s.%(msecs)03d %(name)s %(levelname)s %(message)s'
    datefmt = '%H:%M:%S'
    the_handler = logging.handlers.RotatingFileHandler(
        osdriver.mbusb_log_file(), 'a', 1024*1024, 5)
    the_handler.setFormatter(logging.Formatter(fmt, datefmt))
    logging.root.addHandler(the_handler)

    if platform.system() == 'Windows':
        import pythoncom
        pythoncom.CoInitialize() 
Example 18
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: log_util.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, filename=None):
        self._filename = filename

        # logger
        self._logger = logging.getLogger('logger')
        # remove default handler
        self._logger.propagate = False

        stream_handler = logging.StreamHandler()
        stream_formatter = logging.Formatter('[%(levelname)8s][%(asctime)s.%(msecs)03d] %(message)s',
                                             datefmt='%Y/%m/%d %H:%M:%S')
        stream_handler.setFormatter(stream_formatter)

        if self._filename is not None:
            file_max_bytes = 10 * 1024 * 1024

            file_handler = logging.handlers.RotatingFileHandler(filename='./log/' + self._filename,
                                                               maxBytes=file_max_bytes,
                                                               backupCount=10)
            file_formatter = logging.Formatter('[%(levelname)8s][%(asctime)s.%(msecs)03d] %(message)s',
                                               datefmt='%Y/%m/%d %H:%M:%S')
            file_handler.setFormatter(file_formatter)
            self._logger.addHandler(file_handler)

        self._logger.addHandler(stream_handler)
        self._logger.setLevel(logging.DEBUG) 
Example 19
Project: macops   Author: google   File: gmacpyutil.py    License: Apache License 2.0 5 votes vote down vote up
def emit(self, record):
    msg = self.format(record)

    if len(msg) > 2000:
      break_loc_pre = 0
      for break_char in ['\n', ' ', '\t']:
        break_loc_pre = msg.rfind(break_char, 1000, 2000)
        break_loc_post = break_loc_pre + 1
        if break_loc_pre > 0:
          break

      if break_loc_pre < 1:
        break_loc_pre = 2000
        break_loc_post = 2000

      r1msg = msg[:break_loc_pre]
      r2msg = 'CONTINUED: %s' % msg[break_loc_post:]

      r1 = logging.LogRecord(
          record.name, record.levelno, record.pathname, record.lineno,
          r1msg, None, None, func=record.funcName)
      r2 = logging.LogRecord(
          record.name, record.levelno, record.pathname, None, r2msg, None, None)

      logging.handlers.SysLogHandler.emit(self, r1)
      self.emit(r2)
    else:
      logging.handlers.SysLogHandler.emit(self, record) 
Example 20
Project: InsightAgent   Author: insightfinder   File: insightfinder.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, cfg="/etc/insightfinder.ini", lvl="INFO", attempts=1, flush_kb=3000):
        """
        Implements an interface that allows metrics to be persisted to InsightFinder.
        Raises a :class:`ValueError` on bad arguments or `Exception` on missing
        configuration section.
        :Parameters:
                - `cfg` (optional) : INI configuration file.
                - `lvl` (optional) : logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
                - `attempts` (optional) : The number of re-connect retries before failing.
                - `flush_kb` (optional) : The size of metric data to send in KB(The actual metrics will have a few statsite metrics too)
        """
        if attempts < 1:
            raise ValueError("Must have at least 1 attempt!")

        attempts = int(attempts)

        #Set up logging
        self.logger = logging.getLogger(__name__)
        # create a file handler
        handler = logging.handlers.RotatingFileHandler('insightfinder.log', mode='w', maxBytes=5*1024*1024,
                                 backupCount=2, encoding=None, delay=0)
        # handler = logging.FileHandler('insightfinder.log')
        handler.setLevel(lvl)
        # create a logging format
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(process)d - %(threadName)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        # add the handlers to the logger
        self.logger.addHandler(handler)
        self.logger.setLevel(lvl)

        self.attempts = attempts
        self.metrics_map = {}
        self.to_send_metrics = []
        self.cfg = cfg
        self.load(cfg)
        self.temp_group_id = 10000
        self.flush_kb = int(flush_kb)
        self._load_grouping() 
Example 21
Project: botbuilder-python   Author: microsoft   File: main.py    License: MIT License 5 votes vote down vote up
def setup_logging():
    """Set up logging."""
    logging.info("Setting up logging infrastructure")

    # Create the rotating log handler
    if not os.path.exists("logs"):
        os.mkdir("logs")
    handler = RotatingFileHandler(
        os.path.join("./logs", "model-runtime.log"),
        maxBytes=5 * 1024 ** 2,  # 5 MB chunks,
        backupCount=5,  # limit to 25 MB logs max
    )

    # Set the formatter
    handler.setFormatter(
        logging.Formatter("%(asctime)s %(name)-12s %(levelname)-8s %(message)s")
    )

    # Setup the root logging with the necessary handlers
    log = logging.getLogger()
    log.addHandler(handler)

    # Set to info for normal processing
    log.setLevel(logging.INFO)


# pylint:disable=unused-argument 
Example 22
Project: botbuilder-python   Author: microsoft   File: main.py    License: MIT License 5 votes vote down vote up
def run():
    """Main entry point for model runtime api."""

    # Register signal handlers.
    logging.info("Preparing signal handlers..")
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    # Set up model cache.
    # If containerizing, suggest initializing the directories (and associated
    # file downloads) be performed during container build time.
    logging.info("Initializing model directories:")
    logging.info("    bert  : %s", options.bert_model_dir)
    logging.info("    bidaf : %s", options.bidaf_model_dir)

    language_helper = LanguageHelper()
    if (
        language_helper.initialize_models(
            options.bert_model_dir, options.bidaf_model_dir
        )
        is False
    ):
        logging.error("Could not initilize model directories.  Exiting..")
        return

    # Build the configuration
    logging.info("Building config..")
    ref_obj = {"language_helper": language_helper}
    app_config = ModelHandler.build_config(ref_obj)

    logging.info("Starting Tornado model runtime service..")
    application = tornado.web.Application(app_config)
    application.listen(options.port)

    # Protect the loop with a try/catch
    try:
        # Start the app and wait for a close
        tornado.ioloop.IOLoop.instance().start()
    finally:
        # handle error with shutting down loop
        tornado.ioloop.IOLoop.instance().stop() 
Example 23
Project: glazier   Author: google   File: logs.py    License: Apache License 2.0 5 votes vote down vote up
def Setup():
  """Sets up the logging environment."""
  build_info = buildinfo.BuildInfo()
  log_file = r'%s\%s' % (GetLogsPath(), constants.BUILD_LOG_FILE)

  debug_fmt = ('%(levelname).1s%(asctime)s.%(msecs)03d %(process)d {} '
               '%(filename)s:%(lineno)d]  %(message)s').format(
                   build_info.ImageID())
  info_fmt = '%(levelname).1s%(asctime)s %(filename)s:%(lineno)d] %(message)s'

  debug_formatter = logging.Formatter(debug_fmt, datefmt=DATE_FMT)
  info_formatter = logging.Formatter(info_fmt, datefmt=DATE_FMT)

  # Set default logger
  logger = logging.getLogger()
  logger.setLevel(logging.DEBUG)
  # Create empty list of handlers to enable multiple streams.
  logger.handlers = []

  # Create console handler and set level
  ch = logging.StreamHandler()
  ch.setLevel(logging.INFO)
  ch.setFormatter(info_formatter)
  logger.addHandler(ch)

  # Create file handler and set level
  try:
    fh = logging.FileHandler(log_file)
  except IOError:
    raise LogError('Failed to open log file %s.' % log_file)
  fh.setLevel(logging.DEBUG)
  fh.setFormatter(debug_formatter)
  logger.addHandler(fh)

  # Create Event Log handler and set level
  if not winpe.check_winpe():
    eh = logging.handlers.NTEventLogHandler('GlazierBuildLog')
    eh.setLevel(logging.DEBUG)
    eh.setFormatter(debug_formatter)
    logger.addHandler(eh) 
Example 24
Project: JJMumbleBot   Author: DuckBoss   File: logging_utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def initialize_logging():
    if not runtime_settings.use_logging:
        return
    from logging.handlers import RotatingFileHandler
    logging.getLogger('chardet.charsetprober').setLevel(logging.INFO)
    log_file_name = f"{global_settings.cfg[C_LOGGING][P_LOG_DIR]}/runtime.log"
    global_settings.log_service = logging.getLogger("RuntimeLogging")
    global_settings.log_service.setLevel(logging.DEBUG)

    handler = RotatingFileHandler(log_file_name, maxBytes=150000, backupCount=int(runtime_settings.max_logs))
    handler.setLevel(logging.INFO)
    log_formatter = logging.Formatter('[%(asctime)s]-[%(levelname)s]-%(message)s')
    handler.setFormatter(log_formatter)
    global_settings.log_service.addHandler(handler) 
Example 25
Project: certidude   Author: laurivosandi   File: __init__.py    License: MIT License 5 votes vote down vote up
def __init__(self):
        app = falcon.API(middleware=NormalizeMiddleware())
        app.req_options.auto_parse_form_urlencoded = True
        self.attach(app)

        # Set up log handlers
        log_handlers = []
        if config.LOGGING_BACKEND == "sql":
            from certidude.mysqllog import LogHandler
            from certidude.api.log import LogResource
            uri = config.cp.get("logging", "database")
            log_handlers.append(LogHandler(uri))
        elif config.LOGGING_BACKEND == "syslog":
            from logging.handlers import SysLogHandler
            log_handlers.append(SysLogHandler())
            # Browsing syslog via HTTP is obviously not possible out of the box
        elif config.LOGGING_BACKEND:
            raise ValueError("Invalid logging.backend = %s" % config.LOGGING_BACKEND)
        from certidude.push import EventSourceLogHandler
        log_handlers.append(EventSourceLogHandler())

        for j in logging.Logger.manager.loggerDict.values():
            if isinstance(j, logging.Logger): # PlaceHolder is what?
                if j.name.startswith("certidude."):
                    j.setLevel(logging.DEBUG)
                    for handler in log_handlers:
                        j.addHandler(handler)

        self.server = make_server("127.0.1.1", self.PORT, app, WSGIServer)
        setproctitle("certidude: %s" % self.NAME) 
Example 26
Project: pseudo-channel   Author: justinemter   File: PseudoDailyScheduleController.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, 
                 server, 
                 token, 
                 clients, 
                 controllerServerPath = '', 
                 controllerServerPort = '8000', 
                 debugMode = False,
                 htmlPseudoTitle = "Daily PseudoChannel"
                 ):

        self.PLEX = PlexServer(server, token)
        self.BASE_URL = server
        self.TOKEN = token
        self.PLEX_CLIENTS = clients
        self.CONTROLLER_SERVER_PATH = controllerServerPath
        self.CONTROLLER_SERVER_PORT = controllerServerPort if controllerServerPort != '' else '80'
        self.DEBUG = debugMode
        self.webserverStarted = False
        self.HTML_PSEUDO_TITLE = htmlPseudoTitle
        try: 
            self.my_logger = logging.getLogger('MyLogger')
            self.my_logger.setLevel(logging.DEBUG)
            self.handler = logging.handlers.SysLogHandler(address = '/dev/log')
            self.my_logger.addHandler(self.handler)
        except:
            pass 
Example 27
Project: jawfish   Author: war-and-code   File: config.py    License: MIT License 5 votes vote down vote up
def fileConfig(fname, defaults=None, disable_existing_loggers=True):
    """
    Read the logging configuration from a ConfigParser-format file.

    This can be called several times from an application, allowing an end user
    the ability to select from various pre-canned configurations (if the
    developer provides a mechanism to present the choices and load the chosen
    configuration).
    """
    import configparser

    cp = configparser.ConfigParser(defaults)
    if hasattr(fname, 'readline'):
        cp.read_file(fname)
    else:
        cp.read(fname)

    formatters = _create_formatters(cp)

    # critical section
    logging._acquireLock()
    try:
        logging._handlers.clear()
        del logging._handlerList[:]
        # Handlers add themselves to logging._handlers
        handlers = _install_handlers(cp, formatters)
        _install_loggers(cp, handlers, disable_existing_loggers)
    finally:
        logging._releaseLock() 
Example 28
Project: jawfish   Author: war-and-code   File: config.py    License: MIT License 5 votes vote down vote up
def _install_handlers(cp, formatters):
    """Install and return handlers"""
    hlist = cp["handlers"]["keys"]
    if not len(hlist):
        return {}
    hlist = hlist.split(",")
    hlist = _strip_spaces(hlist)
    handlers = {}
    fixups = [] #for inter-handler references
    for hand in hlist:
        section = cp["handler_%s" % hand]
        klass = section["class"]
        fmt = section.get("formatter", "")
        try:
            klass = eval(klass, vars(logging))
        except (AttributeError, NameError):
            klass = _resolve(klass)
        args = section["args"]
        args = eval(args, vars(logging))
        h = klass(*args)
        if "level" in section:
            level = section["level"]
            h.setLevel(logging._levelNames[level])
        if len(fmt):
            h.setFormatter(formatters[fmt])
        if issubclass(klass, logging.handlers.MemoryHandler):
            target = section.get("target", "")
            if len(target): #the target handler may not be loaded yet, so keep for later...
                fixups.append((h, target))
        handlers[hand] = h
    #now all handlers are loaded, fixup inter-handler references...
    for h, t in fixups:
        h.setTarget(handlers[t])
    return handlers 
Example 29
Project: jawfish   Author: war-and-code   File: config.py    License: MIT License 5 votes vote down vote up
def add_handlers(self, logger, handlers):
        """Add handlers to a logger from a list of names."""
        for h in handlers:
            try:
                logger.addHandler(self.config['handlers'][h])
            except Exception as e:
                raise ValueError('Unable to add handler %r: %s' % (h, e)) 
Example 30
Project: circleci-demo-python-flask   Author: CircleCI-Public   File: config.py    License: MIT License 5 votes vote down vote up
def init_app(cls, app):
        ProductionConfig.init_app(app)

        # log to syslog
        import logging
        from logging.handlers import SysLogHandler
        syslog_handler = SysLogHandler()
        syslog_handler.setLevel(logging.WARNING)
        app.logger.addHandler(syslog_handler)