Initialize Log Analytics mgmt client for use with CLI.
347071
def applicationinsights_mgmt_plane_client(cli_ctx, _, subscription=None):
    """"""
    from .vendored_sdks.mgmt_applicationinsights import ApplicationInsightsManagementClient
    from azure.cli.core._profile import Profile
    profile = Profile(cli_ctx=cli_ctx)
    # Use subscription from resource_id where possible, otherwise use login.
    if subscription:
        cred, _, _ = profile.get_login_credentials(subscription_id=subscription)
        return ApplicationInsightsManagementClient(
            cred,
            subscription
        )
    cred, sub_id, _ = profile.get_login_credentials()
    return ApplicationInsightsManagementClient(
        cred,
        sub_id
    )
985022
def setup_logging(cli_options):
    """"""
    if cli_options.debug_info or get_debug_level() > 0:
        levels = {2: logging.INFO, 3: logging.DEBUG}
        log_level = levels[get_debug_level()]
        log_format = '%(asctime)s [%(levelname)s] [%(name)s] -> %(message)s'

        if cli_options.debug_output == 'file':
            log_file = 'spyder-debug.log'
        else:
            log_file = None

        logging.basicConfig(level=log_level,
                            format=log_format,
                            filename=log_file,
                            filemode='w+')
13830
def init_logging():
    """"""
    with open(os.path.join(os.path.dirname(__file__),'logging.conf'), 'r') as yf:
        config = yaml.load(yf)
    logging.config.dictConfig(config)
842121
def _initialize_manager(self, runtime):
        """"""
        if self._runtime is not None:
            raise errors.IllegalState('this manager has already been initialized.')
        self._runtime = runtime
        self._config = runtime.get_configuration()
        set_json_client(runtime)
118840
def init(main_dir: Path, logfile_path: Path, log_level: str):
    
    dynamic_data.reset()
    dynamic_data.init_dirs(main_dir, logfile_path)

    dynamic_data.check_dirs()

    tools.create_dir_rec(dynamic_data.MAIN_DIR)
    tools.create_dir_rec(dynamic_data.TEMP_DIR)
    tools.create_dir_rec(dynamic_data.DOWNLOAD_DIR)
    tools.create_dir_rec(dynamic_data.SAVESTAT_DIR)
    tools.create_dir_rec(Path.resolve(dynamic_data.LOGFILE_PATH).parent)
    dynamic_data.LOG_LEVEL = log_level
    logging.basicConfig(filename=dynamic_data.LOGFILE_PATH, filemode='a', level=dynamic_data.LOG_LEVEL,
                        format='%(asctime)s.%(msecs)03d | %(levelname)s - %(name)s | %(module)s.%(funcName)s: %('
                               'message)s',
                        datefmt='%Y.%m.%d %H:%M:%S')
    logging.captureWarnings(True)

    cores = multiprocessing.cpu_count()
    dynamic_data.USING_CORES = min(4, max(1, cores - 1))

    info = f"{static_data.NAME} {static_data.VERSION}\n\n" \
           f"System: {platform.system()} - {platform.version()} - {platform.machine()} - {cores} cores\n" \
           f"Python: {platform.python_version()} - {' - '.join(platform.python_build())}\n" \
           f"Arguments: main={main_dir.resolve()} | logfile={logfile_path.resolve()} | loglevel={log_level}\n" \
           f"Using cores: {dynamic_data.USING_CORES}\n\n"
    with dynamic_data.LOGFILE_PATH.open(mode='w', encoding="utf8") as writer:
        writer.write(info)

    dynamic_data.AVAIL_PLUGINS = APlugin.get_plugins()
565758
def cli(ctx, board, scons, project_dir, sayyes):
    """"""

    if scons:
        Project().create_sconstruct(project_dir, sayyes)
    elif board:
        Project().create_ini(board, project_dir, sayyes)
    else:
        click.secho(ctx.get_help())
493676
def logger_init():
    """"""
    log = logging.getLogger("pyinotify")
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(
        logging.Formatter("[%(asctime)s %(name)s %(levelname)s] %(message)s"))
    log.addHandler(console_handler)
    log.setLevel(20)
    return log
302328
def _init_logging(verbose):
    """"""
    hdlr = logging.StreamHandler()
    hdlr.setFormatter(logging.Formatter(
        '%(asctime)s [%(levelname)s] [%(module)s] %(message)s'))
    LOG.addHandler(hdlr)
    if verbose:
        LOG.setLevel(logging.DEBUG)
        LOG.debug('Verbose output enabled.')
    else:
        LOG.setLevel(logging.INFO)
994529
def cli(action, config_file, debug, verbose):
    
    if verbose is True:
        log_level = 'DEBUG'
    elif verbose is False:
        log_level = 'WARNING'
    else:
        assert verbose is None
        log_level = 'INFO'

    setup_logging(log_level)
    try:
        grab = Grab(config_file, debug=debug)
        if action in {'download', None}:
            grab.download()
        if action in {'build', None}:
            grab.build()
    except GrablibError as e:
        click.secho('Error: %s' % e, fg='red')
        sys.exit(2)
1209474
def setup_prometheus(self, registry=None):
        """"""
        kwargs = {}
        if registry:
            kwargs["registry"] = registry
        self.metrics = PrometheusMetrics(self.app, **kwargs)
        try:
            version = pkg_resources.require(self.app.name)[0].version
        except pkg_resources.DistributionNotFound:
            version = "unknown"
        self.metrics.info(
            "app_info", "Application info", version=version, appname=self.app.name
        )
        self.app.logger.info("Prometheus is enabled.")
108046
public void initializeLogger(String log4jConfigurationPath) {
		if (isBlank(System.getProperty(LOG4J2_PROPERTY)) && !isBlank(log4jConfigurationPath)) {
			File log4jFile = new File(log4jConfigurationPath);
			if (log4jFile.exists()) {
				String log4jUrl;
				try {
					log4jUrl = log4jFile.toURI().toURL().toString();
				}
				catch (MalformedURLException ex) {
					log4jUrl = "file:" + log4jConfigurationPath;
				}
				System.setProperty(LOG4J2_PROPERTY, log4jUrl);
			}
		}
		// Install JUL bridge
		System.setProperty(JUL_MANAGER, LogManager.class.getName());
	}
287889
def _init_catalog(self, proxy=None, runtime=None):
        """"""
        self._init_proxy_and_runtime(proxy, runtime)
        osid_name = self._session_namespace.split('.')[0]
        try:
            config = self._runtime.get_configuration()
            parameter_id = Id('parameter:' + osid_name + 'CatalogingProviderImpl@mongo')
            provider_impl = config.get_value_by_parameter(parameter_id).get_string_value()
            self._cataloging_manager = self._runtime.get_manager('CATALOGING', provider_impl)  # need to add version argument
        except (AttributeError, KeyError, errors.NotFound):
            pass
1225029
def initialize_logging(args):
    """"""
    log_handler = logging.StreamHandler()
    log_formatter = logging.Formatter(
        "%(levelname)s %(asctime)s %(name)s:%(lineno)04d - %(message)s")
    log_handler.setFormatter(log_formatter)

    root_logger = logging.getLogger()
    root_logger.addHandler(log_handler)
    root_logger.setLevel(getattr(logging, args.loglevel))
720431
def launch(run=True, **args):
    """"""

    verbosity['console'] = args['log'] if not args['quiet'] else 100
    verbosity['global'] = min(args['log'], args['logfileverbosity'])
    verbosity['file'] = args['logfileverbosity'] if args['dolog'] else 100
    set_logfile(args['logfilepath'], args['instance'])

    if args['livelog'] is True:
        from hfos import logger
        logger.live = True

    hfoslog("Running with Python", sys.version.replace("\n", ""),
            sys.platform, lvl=debug, emitter='CORE')
    hfoslog("Interpreter executable:", sys.executable, emitter='CORE')
    if args['cert'] is not None:
        hfoslog("Warning! Using SSL without nginx is currently not broken!",
                lvl=critical, emitter='CORE')

    hfoslog("Initializing database access", emitter='CORE', lvl=debug)
    initialize(args['dbhost'], args['dbname'], args['instance'])

    server = construct_graph(args)
    if run and not args['norun']:
        server.run()

    return server
932006
def init(self):
        """"""
        if not self.export_enable:
            return None

        self.index='{}-{}'.format(self.index, datetime.utcnow().strftime("%Y.%m.%d"))
        template_body =  {
          "mappings": {
            "glances": {
              "dynamic_templates": [
                {
                  "integers": {
                    "match_mapping_type": "long",
                    "mapping": {
                      "type": "integer"
                    }
                  }
                },
                {
                  "strings": {
                    "match_mapping_type": "string",
                    "mapping": {
                      "type": "text",
                      "fields": {
                        "raw": {
                          "type":  "keyword",
                          "ignore_above": 256
                        }
                      }
                    }
                  }
                }
              ]
            }
          }
        }

        try:
            es = Elasticsearch(hosts=['{}:{}'.format(self.host, self.port)])
        except Exception as e:
            logger.critical("Cannot connect to ElasticSearch server %s:%s (%s)" % (self.host, self.port, e))
            sys.exit(2)
        else:
            logger.info("Connected to the ElasticSearch server %s:%s" % (self.host, self.port))

        try:
            index_count = es.count(index=self.index)['count']
        except Exception as e:
            # Index did not exist, it will be created at the first write
            # Create it...
            es.indices.create(index=self.index,body=template_body)
        else:
            logger.info("The index %s exists and holds %s entries." % (self.index, index_count))

        return es
587710
def _init(board, project_dir):
    
    project_dir = os.path.abspath(project_dir)

    # Initialize the platformio project
    pio_config_path = os.path.join(project_dir, "platformio.ini")
    if not os.path.isfile(pio_config_path):
        click.echo("Initializing PlatformIO project")
        with open("/dev/null", "wb") as null:
            try:
                init = subprocess.Popen(
                    ["platformio", "init", "-b", board], stdin=subprocess.PIPE,
                    stdout=null, cwd=project_dir
                )
                init.communicate("y\n")
            except OSError as e:
                raise RuntimeError("PlatformIO is not installed")
        if init.returncode != 0:
            raise RuntimeError(
                "Failed to initialize PlatformIO project"
            )
    click.echo("OpenAg firmware project initialized!")
583622
def initialize_logging(self):
        """"""
        # Reset logging to pass logrecords into the queue to the frontend only.
        # Existing handlers may be broken as they were copied into a new process,
        # so should be discarded.
        for loggername in [None] + list(logging.Logger.manager.loggerDict.keys()):
            logger = logging.getLogger(loggername)
            while logger.handlers:
                logger.removeHandler(logger.handlers[0])

        # Re-enable logging to console
        root_logger = logging.getLogger()

        # By default pass all warning (and higher) level messages to the frontend
        root_logger.setLevel(logging.WARN)
        root_logger.addHandler(workflows.logging.CallbackHandler(self._log_send))

        # Set up the service logger and pass all info (and higher) level messages
        # (or other level if set differently)
        self.log = logging.getLogger(self._logger_name)

        if self.start_kwargs.get("verbose_log"):
            self.log_verbosity = logging.DEBUG
        self.log.setLevel(self.log_verbosity)

        # Additionally, write all critical messages directly to console
        console = logging.StreamHandler()
        console.setLevel(logging.CRITICAL)
        root_logger.addHandler(console)