Install handlers for Mitogen loggers to redirect them into the Ansible
    display framework. Ansible installs its own logging framework handlers when
    C.DEFAULT_LOG_PATH is set, therefore disable propagation for our handlers.
505283
def setup():
    
    l_mitogen = logging.getLogger('mitogen')
    l_mitogen_io = logging.getLogger('mitogen.io')
    l_ansible_mitogen = logging.getLogger('ansible_mitogen')

    for logger in l_mitogen, l_mitogen_io, l_ansible_mitogen:
        logger.handlers = [Handler(display.vvv)]
        logger.propagate = False

    if display.verbosity > 2:
        l_ansible_mitogen.setLevel(logging.DEBUG)
        l_mitogen.setLevel(logging.DEBUG)
    else:
        # Mitogen copies the active log level into new children, allowing them
        # to filter tiny messages before they hit the network, and therefore
        # before they wake the IO loop. Explicitly setting INFO saves ~4%
        # running against just the local machine.
        l_mitogen.setLevel(logging.ERROR)
        l_ansible_mitogen.setLevel(logging.ERROR)

    if display.verbosity > 3:
        l_mitogen_io.setLevel(logging.DEBUG)
688116
public static void init() {
        logger = Logger.getLogger("");
        final Handler[] handlers = logger.getHandlers();
        // In regular Java there is always a handler. Avian doesn't install one however.
        if (handlers.length > 0)
            handlers[0].setFormatter(new BriefLogFormatter());
    }
1174356
def init_logger(root_dir, name="train.log"):
    
    os.makedirs(root_dir, exist_ok=True)
    log_formatter = logging.Formatter("%(message)s")
    logger = logging.getLogger(name)
    file_handler = logging.FileHandler("{0}/{1}".format(root_dir, name), mode='w')
    file_handler.setFormatter(log_formatter)
    logger.addHandler(file_handler)
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(log_formatter)
    logger.addHandler(console_handler)
    logger.setLevel(logging.INFO)
    return logger
589107
def _add_plugin_paths(self):
        
        base_dir = os.path.join(os.path.dirname(__file__), 'plugins')
        ansible_mitogen.loaders.connection_loader.add_directory(
            os.path.join(base_dir, 'connection')
        )
        ansible_mitogen.loaders.action_loader.add_directory(
            os.path.join(base_dir, 'action')
        )
1117109
def setup_handler(context):
    

    if context.readDataFile("bika.lims_various.txt") is None:
        return

    logger.info(" [BEGIN]")

    portal = context.getSite()

    # Run Installers
    remove_default_content(portal)
    hide_navbar_items(portal)
    reindex_content_structure(portal)
    setup_groups(portal)
    setup_catalog_mappings(portal)
    setup_core_catalogs(portal)

    # Setting up all LIMS catalogs defined in catalog folder
    setup_catalogs(portal, getCatalogDefinitions())

    # Run after all catalogs have been setup
    setup_auditlog_catalog(portal)

    logger.info(" [DONE]")
1047246
def install_logger(logger=None, module=None):
    

    logger = logging.getLogger(Constants.logger) if logger is None else logger
    if module is None:
        # Note: inspect.getmodule() can return the wrong module if it has been imported with different relatives paths.
        module = sys.modules.get(inspect.currentframe().f_back.f_globals["__name__"])
    setattr(module, "LOGGER", logger)

    foundations.trace.register_module(module)

    return logger
122786
def configureLogger(self):
        
        baseLogLevel = logging.DEBUG if self.isDebugLogging() else logging.INFO
        # create recorder app root logger
        logger = logging.getLogger(self._name)
        logger.setLevel(baseLogLevel)
        # file handler
        fh = handlers.RotatingFileHandler(path.join(self._getConfigPath(), self._name + '.log'),
                                          maxBytes=10 * 1024 * 1024, backupCount=10)
        fh.setLevel(baseLogLevel)
        # create console handler with a higher log level
        ch = logging.StreamHandler()
        ch.setLevel(logging.WARN)
        # create formatter and add it to the handlers
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(funcName)s - %(message)s')
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
        # add the handlers to the logger
        logger.addHandler(fh)
        logger.addHandler(ch)
        return logger
84190
def setup_logging(default_json_path=None, default_level=None, env_key='LOG_CFG',
                  custom_log_dir=None):
    

    if not default_json_path:
        default_json_path = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), "logging.json")
    path = default_json_path
    value = os.getenv(env_key, None)
    if value:
        path = value

    if os.path.exists(path):
        with open(path, 'rt') as f:
            config = json.load(f)

        log_dir = os.path.abspath(prms.Paths["filelogdir"])

        if custom_log_dir:
            log_dir = custom_log_dir

        if not os.path.isdir(log_dir):
            warning_txt = ("\nCould not set custom log-dir - "
                           "non-existing directory"
                           f"\nDir: {log_dir}"
                           "\nUsing current directory instead: "
                           f"{os.getcwd()}")
            logging.warning(warning_txt)
            log_dir = os.getcwd()

        for file_handler in ["error_file_handler", "info_file_handler",
                             "debug_file_handler"]:
            try:
                file_name = config["handlers"][file_handler]["filename"]
                logging.debug("Setting file handlers for logging.")
                logging.debug(f"Filename: {file_name}")
                logging.debug(f"Full path: {os.path.join(log_dir,file_name)}")
                # print(f"Filename: {file_name}")
                # print(f"Full path: {os.path.join(log_dir,file_name)}")
                config["handlers"][file_handler][
                    "filename"] = os.path.join(log_dir,
                                               file_name)
            except Exception as e:
                warnings.warn("\nCould not set custom log-dir" + str(e))

        if default_level:
            w_txt = "\nCould not set custom default level for logger"
            if default_level not in [
                "INFO", "DEBUG", logging.INFO, logging.DEBUG
            ]:
                _txt = "\nonly 'INFO' and 'DEBUG' is supported"
                _txt += " as default_level"
                warnings.warn(w_txt + _txt)

            else:
                try:
                    config["handlers"]["console"]["level"] = default_level
                    if default_level in ["DEBUG", logging.DEBUG]:
                        config["handlers"]["console"]["formatter"] = "stamped"

                except Exception as e:
                    warnings.warn(w_txt + "\n" + str(e))

        logging.config.dictConfig(config)
    else:
        if not default_level:
            default_level = logging.INFO
        logging.basicConfig(level=default_level)
384370
def _setup_master(self):
        
        self.broker = mitogen.master.Broker(install_watcher=False)
        self.router = mitogen.master.Router(
            broker=self.broker,
            max_message_size=4096 * 1048576,
        )
        self._setup_responder(self.router.responder)
        mitogen.core.listen(self.broker, 'shutdown', self.on_broker_shutdown)
        mitogen.core.listen(self.broker, 'exit', self.on_broker_exit)
        self.listener = mitogen.unix.Listener(
            router=self.router,
            path=self.unix_listener_path,
            backlog=C.DEFAULT_FORKS,
        )
        self._enable_router_debug()
        self._enable_stack_dumps()
492480
def logging_config(logpath=None,
                   level=logging.DEBUG,
                   console_level=logging.INFO,
                   no_console=False):
    
    logger = logging.getLogger('nli')
    # Remove all the current handlers
    for handler in logger.handlers:
        logger.removeHandler(handler)
    logger.handlers = []
    logger.propagate = False
    logger.setLevel(logging.DEBUG)

    formatter = logging.Formatter('%(filename)s:%(funcName)s: %(message)s')

    if logpath is not None:
        print('All Logs will be saved to {}'.format(logpath))
        logfile = logging.FileHandler(logpath, mode='w')
        logfile.setLevel(level)
        logfile.setFormatter(formatter)
        logger.addHandler(logfile)

    if not no_console:
        # Initialze the console logging
        logconsole = logging.StreamHandler()
        logconsole.setLevel(console_level)
        logconsole.setFormatter(formatter)
        logger.addHandler(logconsole)
1107806
def capture(package, prefix, modules=[], level=logging.DEBUG):
    
    handler = LogFileHandler(package, prefix)
    formatter = logging.Formatter(FORMAT)
    handler.setFormatter(formatter)
    modules = set(modules + ['loadkit'])

    for logger in modules:
        if not hasattr(logger, 'addHandler'):
            logger = logging.getLogger(logger)
        logger.setLevel(level=level)
        logger.addHandler(handler)

    return handler
450722
def setup_handlers():
    '''
    
    '''
    __grains__ = salt.loader.grains(__opts__)
    __salt__ = salt.loader.minion_mods(__opts__)
    if 'sentry_handler' not in __opts__:
        log.debug('No \'sentry_handler\' key was found in the configuration')
        return False
    options = {}
    dsn = get_config_value('dsn')
    if dsn is not None:
        try:
            # support raven ver 5.5.0
            from raven.transport import TransportRegistry, default_transports
            from raven.utils.urlparse import urlparse
            transport_registry = TransportRegistry(default_transports)
            url = urlparse(dsn)
            if not transport_registry.supported_scheme(url.scheme):
                raise ValueError('Unsupported Sentry DSN scheme: {0}'.format(url.scheme))
        except ValueError as exc:
            log.info(
                'Raven failed to parse the configuration provided DSN: %s', exc
            )

    if not dsn:
        for key in ('project', 'servers', 'public_key', 'secret_key'):
            config_value = get_config_value(key)
            if config_value is None and key not in options:
                log.debug(
                    'The required \'sentry_handler\' configuration key, '
                    '\'%s\', is not properly configured. Not configuring '
                    'the sentry logging handler.', key
                )
                return
            elif config_value is None:
                continue
            options[key] = config_value

    # site: An optional, arbitrary string to identify this client installation.
    options.update({
        # site: An optional, arbitrary string to identify this client
        # installation
        'site': get_config_value('site'),

        # name: This will override the server_name value for this installation.
        # Defaults to socket.gethostname()
        'name': get_config_value('name'),

        # exclude_paths: Extending this allow you to ignore module prefixes
        # when sentry attempts to discover which function an error comes from
        'exclude_paths': get_config_value('exclude_paths', ()),

        # include_paths: For example, in Django this defaults to your list of
        # INSTALLED_APPS, and is used for drilling down where an exception is
        # located
        'include_paths': get_config_value('include_paths', ()),

        # list_max_length: The maximum number of items a list-like container
        # should store.
        'list_max_length': get_config_value('list_max_length'),

        # string_max_length: The maximum characters of a string that should be
        # stored.
        'string_max_length': get_config_value('string_max_length'),

        # auto_log_stacks: Should Raven automatically log frame stacks
        # (including locals) all calls as it would for exceptions.
        'auto_log_stacks': get_config_value('auto_log_stacks'),

        # timeout: If supported, the timeout value for sending messages to
        # remote.
        'timeout': get_config_value('timeout', 1),

        # processors: A list of processors to apply to events before sending
        # them to the Sentry server. Useful for sending additional global state
        # data or sanitizing data that you want to keep off of the server.
        'processors': get_config_value('processors'),

        # dsn: Ensure the DSN is passed into the client
        'dsn': dsn
    })

    client = raven.Client(**options)
    context = get_config_value('context')
    context_dict = {}
    if context is not None:
        for tag in context:
            try:
                tag_value = __grains__[tag]
            except KeyError:
                log.debug('Sentry tag \'%s\' not found in grains.', tag)
                continue
            if tag_value:
                context_dict[tag] = tag_value
        if context_dict:
            client.context.merge({'tags': context_dict})
    try:
        handler = SentryHandler(client)

        exclude_patterns = get_config_value('exclude_patterns', None)
        if exclude_patterns:
            filter_regexes = [re.compile(pattern) for pattern in exclude_patterns]

            class FilterExcludedMessages(object):
                @staticmethod
                def filter(record):
                    m = record.getMessage()
                    return not any(regex.search(m) for regex in filter_regexes)

            handler.addFilter(FilterExcludedMessages())

        handler.setLevel(LOG_LEVELS[get_config_value('log_level', 'error')])
        return handler
    except ValueError as exc:
        log.debug('Failed to setup the sentry logging handler', exc_info=True)
314279
def __remove_null_logging_handler():
    '''
    
    '''
    global LOGGING_NULL_HANDLER
    if LOGGING_NULL_HANDLER is None:
        # Already removed
        return

    root_logger = logging.getLogger()

    for handler in root_logger.handlers:
        if handler is LOGGING_NULL_HANDLER:
            root_logger.removeHandler(LOGGING_NULL_HANDLER)
            # Redefine the null handler to None so it can be garbage collected
            LOGGING_NULL_HANDLER = None
            break
1098756
def _setup_services(self):
        
        self.pool = mitogen.service.Pool(
            router=self.router,
            services=[
                mitogen.service.FileService(router=self.router),
                mitogen.service.PushFileService(router=self.router),
                ansible_mitogen.services.ContextService(self.router),
                ansible_mitogen.services.ModuleDepService(self.router),
            ],
            size=getenv_int('MITOGEN_POOL_SIZE', default=32),
        )
        LOG.debug('Service pool configured: size=%d', self.pool.size)
400491
def _setup_logging(conf):
    
    if conf['verbose']:
        level = logging.DEBUG
    else:
        level = logging.INFO

    fname = conf['logfile'] if conf['logfile'] != "-" else None

    logging.basicConfig(filename=fname, level=level,
                        format='%(asctime)s - %(levelname)-8s - '
                               '%(threadName)-15s - %(message)s')

    # Don't want to see all the messages from BOTO and watchdog
    logging.getLogger('boto').setLevel(logging.CRITICAL)
    logging.getLogger('watchdog.observers.inotify_buffer'). \
                                                setLevel(logging.CRITICAL)
367111
def setup_logger(logger, stream, filename=None, fmt=None):
    
    if len(logger.handlers) < 1:
        console = logging.StreamHandler(stream)
        console.setLevel(logging.DEBUG)
        console.setFormatter(logging.Formatter(fmt))
        logger.addHandler(console)
        logger.setLevel(logging.DEBUG)
        logger.propagate = False

        if filename:
            outfile = logging.FileHandler(filename)
            outfile.setLevel(logging.INFO)
            outfile.setFormatter(logging.Formatter("%(asctime)s " + (fmt if fmt else '%(message)s')))
            logger.addHandler(outfile)
383180
def setup_logger(logging_level, logging_format):
    """"""
    logger = logging.getLogger("ray")
    if type(logging_level) is str:
        logging_level = logging.getLevelName(logging_level.upper())
    logger.setLevel(logging_level)
    global _default_handler
    if _default_handler is None:
        _default_handler = logging.StreamHandler()
        logger.addHandler(_default_handler)
    _default_handler.setFormatter(logging.Formatter(logging_format))
    logger.propagate = False