initialize a Logger for tracking hits to the server
1242
def init_access_log
      return if access_log_dest.nil?

      log = ::Logging.logger['access_log']
      pattern = ::Logging.layouts.pattern(:pattern => ACCESS_LOG_PATTERN)

      log.add_appenders(
        ::Logging.appenders.rolling_file(access_log_dest,
          :level => :debug,
          :age => 'daily',
          :layout => pattern)
        )

      log
    end
528227
def initLogger():
    '''
    
    '''
    global logger
    logger = logging.getLogger('root')
    logger.setLevel(logging.DEBUG)
    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(logging.INFO)
    formatter = logging.Formatter("[%(asctime)s] %(levelname)s: %(message)s", "%Y-%m-%d %H:%M:%S")
    ch.setFormatter(formatter)
    logger.addHandler(ch)
548993
def ClientInit():
  """"""
  metric_metadata = client_metrics.GetMetadata()
  metric_metadata.extend(communicator.GetMetricMetadata())
  stats_collector_instance.Set(
      default_stats_collector.DefaultStatsCollector(metric_metadata))

  config_lib.SetPlatformArchContext()
  config_lib.ParseConfigCommandLine()

  client_logging.LogInit()
  all_parsers.Register()
  registry.Init()

  if not config.CONFIG.ContextApplied(contexts.CLIENT_BUILD_CONTEXT):
    config.CONFIG.Persist("Client.labels")
    config.CONFIG.Persist("Client.proxy_servers")
    config.CONFIG.Persist("Client.tempdir_roots")
350289
function initFileLogger(filepath) {
  currentFilePath = filepath || currentFilePath;

  var logDir = path.dirname(currentFilePath);
  appenders.push(logToFile);
  if(!fs.existsSync(logDir)) fs.mkdirSync(logDir);
}
769792
function Logger_createReadLogServer() {
            var that = this;
            this.server = new HttpServer();
            this.server.on('request', function (request, response) {
                var startMessage = 'LAST '+ that.config.readLength + ' BYTES:\n\n';

                fs.open(that.file, 'r', 755, function(status, fd) {
                    fs.fstat(fd, function (err, stats) {
                        var size = stats.size,
                            start = size > that.config.readLength ? size - that.config.readLength : 0,
                            end = size > that.config.readLength ? that.config.readLength : size,
                            buffer =  new Buffer(end + startMessage.length);
                        buffer.fill(startMessage);
                        fs.read(fd, buffer, startMessage.length, end, start, function() {
                            response.writeHead(200, {'Content-type': 'text/plain', 'Content-Length': buffer.length});
                            response.end(buffer);
                        });
                    });
                });

            });

            this.server.listen(this.config.port);

            this.info('Publishing log write stream on port: ', this.config.port);
        }
987908
def initLogging(verbosity=0, name="SCOOP"):
        """"""
        global loggingConfig

        verbose_levels = {
            -2: "CRITICAL",
            -1: "ERROR",
            0: "WARNING",
            1: "INFO",
            2: "DEBUG",
            3: "DEBUG",
            4: "NOSET",
        }
        log_handlers = {
            "console":
            {
                "class": "logging.StreamHandler",
                "formatter": "{name}Formatter".format(name=name),
                "stream": "ext://sys.stderr",
            },
        }
        loggingConfig.update({
            "{name}Logger".format(name=name):
            {
                "handlers": ["console"],
                "level": verbose_levels[verbosity],
            },
        })
        dict_log_config = {
            "version": 1,
            "handlers": log_handlers,
            "loggers": loggingConfig,
            "formatters":
            {
                "{name}Formatter".format(name=name):
                {
                    "format": "[%(asctime)-15s] %(module)-9s "
                              "%(levelname)-7s %(message)s",
                },
            },
        }
        dictConfig(dict_log_config)
        return logging.getLogger("{name}Logger".format(name=name))
741171
def initialize(self, run_tracker, all_options, start_time=None):
    

    run_id, run_uuid = run_tracker.initialize(all_options)
    run_dir = os.path.join(self.get_options().reports_dir, run_id)

    html_dir = os.path.join(run_dir, 'html')
    safe_mkdir(html_dir)
    relative_symlink(run_dir, os.path.join(self.get_options().reports_dir, 'latest'))

    report = Report()

    # Capture initial console reporting into a buffer. We'll do something with it once
    # we know what the cmd-line flag settings are.
    outfile = BytesIO()
    errfile = BytesIO()
    capturing_reporter_settings = PlainTextReporter.Settings(
      outfile=outfile, errfile=errfile, log_level=Report.INFO,
      color=False, indent=True, timing=False,
      cache_stats=False,
      label_format=self.get_options().console_label_format,
      tool_output_format=self.get_options().console_tool_output_format)
    capturing_reporter = PlainTextReporter(run_tracker, capturing_reporter_settings)
    report.add_reporter('capturing', capturing_reporter)

    # Set up HTML reporting. We always want that.
    html_reporter_settings = HtmlReporter.Settings(log_level=Report.INFO,
                                                   html_dir=html_dir,
                                                   template_dir=self.get_options().template_dir)
    html_reporter = HtmlReporter(run_tracker, html_reporter_settings)
    report.add_reporter('html', html_reporter)

    # Set up Zipkin reporting.
    zipkin_endpoint = self.get_options().zipkin_endpoint
    trace_id = self.get_options().zipkin_trace_id
    parent_id = self.get_options().zipkin_parent_id
    sample_rate = self.get_options().zipkin_sample_rate

    if zipkin_endpoint is None and trace_id is not None and parent_id is not None:
      raise ValueError(
        "The zipkin-endpoint flag must be set if zipkin-trace-id and zipkin-parent-id flags are given."
      )
    if (trace_id is None) != (parent_id is None):
      raise ValueError(
        "Flags zipkin-trace-id and zipkin-parent-id must both either be set or not set."
      )

    # If trace_id isn't set by a flag, use UUID from run_id
    if trace_id is None:
      trace_id = run_uuid

    if trace_id and (len(trace_id) != 16 and len(trace_id) != 32 or not is_hex_string(trace_id)):
      raise ValueError(
        "Value of the flag zipkin-trace-id must be a 16-character or 32-character hex string. "
        + "Got {}.".format(trace_id)
      )
    if parent_id and (len(parent_id) != 16 or not is_hex_string(parent_id)):
      raise ValueError(
        "Value of the flag zipkin-parent-id must be a 16-character hex string. "
        + "Got {}.".format(parent_id)
      )

    if zipkin_endpoint is not None:
      zipkin_reporter_settings = ZipkinReporter.Settings(log_level=Report.INFO)
      zipkin_reporter = ZipkinReporter(
        run_tracker, zipkin_reporter_settings, zipkin_endpoint, trace_id, parent_id, sample_rate
      )
      report.add_reporter('zipkin', zipkin_reporter)

    # Add some useful RunInfo.
    run_tracker.run_info.add_info('default_report', html_reporter.report_path())
    port = ReportingServerManager().socket
    if port:
      run_tracker.run_info.add_info('report_url', 'http://localhost:{}/run/{}'.format(port, run_id))

    # And start tracking the run.
    run_tracker.start(report, start_time)
493823
def logger(self):
        """"""
        try:
            return self._logger
        except AttributeError:
            name = '%s.%s' % (self.__module__, self.__class__.__name__)
            self._logger = logging.getLogger(name)
            self.logger.debug('Initializing...')
            return self._logger
612996
def setup_logger(log=None, level=logging.INFO):
    
    if not log:
        log = logging.getLogger()
    if not log.handlers:
        channel = logging.StreamHandler()
        if level == logging.DEBUG:
            channel.setFormatter(DebugLogFormatter())
        else:
            channel.setFormatter(LogFormatter())

        log.setLevel(level)
        log.addHandler(channel)
693658
def setup_logging(log_level=logging.INFO):
    """"""
    logging.basicConfig(level=log_level)
    fmt = ("%(asctime)s %(levelname)s (%(threadName)s) "
           "[%(name)s] %(message)s")
    colorfmt = "%(log_color)s{}%(reset)s".format(fmt)
    datefmt = '%Y-%m-%d %H:%M:%S'

    # Suppress overly verbose logs from libraries that aren't helpful
    logging.getLogger('requests').setLevel(logging.WARNING)

    try:
        from colorlog import ColoredFormatter
        logging.getLogger().handlers[0].setFormatter(ColoredFormatter(
            colorfmt,
            datefmt=datefmt,
            reset=True,
            log_colors={
                'DEBUG': 'cyan',
                'INFO': 'green',
                'WARNING': 'yellow',
                'ERROR': 'red',
                'CRITICAL': 'red',
            }
        ))
    except ImportError:
        pass

    logger = logging.getLogger('')
    logger.setLevel(log_level)
399973
def init_logging(log_level):
    
    log_level = log_level_to_string_map[min(log_level, 5)]

    msg = "%(levelname)s - %(name)s:%(lineno)s - %(message)s" if log_level in os.environ else "%(levelname)s - %(message)s"

    logging_conf = {
        "version": 1,
        "root": {
            "level": log_level,
            "handlers": ["console"]
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "level": log_level,
                "formatter": "simple",
                "stream": "ext://sys.stdout"
            }
        },
        "formatters": {
            "simple": {
                "format": " {0}".format(msg)
            }
        }
    }

    logging.config.dictConfig(logging_conf)
143441
def _setup_logger(self, level, log_file):
        """"""
        if logger.handlers:
            return
        level = getattr(logging, level.upper())
        logger.setLevel(level)
        formatter = logging.Formatter(
            '[%(levelname)s] %(asctime)s - %(module)s.%(funcName)s() - %(message)s')
        handler = logging.StreamHandler()
        logger.addHandler(handler)
        handler.setFormatter(formatter)
        if not log_file:
            return
        try:
            handler = TimedRotatingFileHandler(log_file)
        except IOError:
            logger.error("Could not write to %s, falling back to stdout",
                         log_file)
        else:
            logger.addHandler(handler)
            handler.setFormatter(formatter)
1340095
def setup_logger(log_level, log_file=None):
    """"""
    level = getattr(logging, log_level.upper(), None)
    if not level:
        color_print("Invalid log level: %s" % log_level, "RED")
        sys.exit(1)

    # hide traceback when log level is INFO/WARNING/ERROR/CRITICAL
    if level >= logging.INFO:
        sys.tracebacklimit = 0

    formatter = ColoredFormatter(
        u"%(log_color)s%(bg_white)s%(levelname)-8s%(reset)s %(message)s",
        datefmt=None,
        reset=True,
        log_colors=log_colors_config
    )

    if log_file:
        handler = logging.FileHandler(log_file, encoding="utf-8")
    else:
        handler = logging.StreamHandler()

    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(level)
1195672
@SuppressWarnings( { "NestedTryStatement" })
    public void init_logger() {
	try {
	    Util.out4.println("Initializing logging for " + get_name());
	    // - Get Util instance
	    final Util util = Util.instance();
	    // - Get cmd line logging level then ...
	    final int trace_level = util.get_trace_level();
	    // ... convert it to log4j level
	    Level cmd_line_level;
	    // does the logging level set from cmd line?
	    boolean level_set_from_cmd_line = true;
	    if (trace_level <= 0) {
		level_set_from_cmd_line = false;
		cmd_line_level = Level.OFF;
	    } else if (trace_level <= 2) {
		cmd_line_level = Level.INFO;
	    } else {
		cmd_line_level = Level.DEBUG;
	    }
	    // - Add a console target if logging level set from cmd line
	    if (level_set_from_cmd_line) {
		// add a console target if logging level set from cmd line
		try {
		    Logging.instance().add_logging_target(get_logger(), LOGGING_CONSOLE_TARGET);
		} catch (final DevFailed df) {
		    /** ignore exception */
		}
	    }
	    if (!Util._UseDb) {
		// - Done if we are not using the database
		Util.out4.println("Not using the database. Logging Intialization complete");
		return;
	    }
	    // - Get both logging level and targets from database
	    final Logging.LoggingProperties properties = Logging.instance().get_logging_properties(
		    get_logger(), util.get_database());
	    if (properties == null) {
		Util.out4.println("Failed to obtain logging properties from database");
		Util.out4.println("Aborting logging intialization");
		get_logger().setLevel(cmd_line_level);
		return;
	    }
	    // - Set logging level
	    if (level_set_from_cmd_line == false) {
		get_logger().setLevel(properties.logging_level);
		Util.out4.println("Logging level set to " + properties.logging_level.toString());
	    } else {
		get_logger().setLevel(cmd_line_level);
	    }
	    // - Save current logging level
	    last_level = get_logger().getLevel();
	    // - Get rolling threshold for file targets
	    if (rft != properties.logging_rft) {
		rft = properties.logging_rft;
		Util.out4.println("Rolling threshold changed to " + String.valueOf(rft));
	    }
	    // - Set logging targets
	    if (properties.logging_targets != null) {
		Util.out4.println("Adding logging targets (" + properties.logging_targets.length
			+ " entries in db)");
		for (final String logging_target : properties.logging_targets) {
		    try {
			Logging.instance().add_logging_target(get_logger(), logging_target);
		    } catch (final DevFailed e) { /* ignore any exception */
		    }
		}
	    }
	    // set rolling file threshold for file targets
	    Logging.instance().set_rolling_file_threshold(get_logger(), rft);
	} catch (final Exception e) {
	    // igore any exception
	}
    }
385848
void checkInitialized(Logger pLogger)
            throws ELException {
        if (!mInitialized) {
            synchronized (this) {
                if (!mInitialized) {
                    initialize(pLogger);
                    mInitialized = true;
                }
            }
        }
    }
656897
def init_log(*handlers, **kwargs):
    
    disable_existing_loggers = kwargs.get('disable_existing_loggers', False)

    handlers_config = [t.get_handler() for t in handlers]
    new_handlers_config = {}
    for t in handlers_config:
        new_handlers_config.update(t)

    formatter_config = [t.get_formatter() for t in handlers]
    new_formatter_config = {}
    for t in formatter_config:
        new_formatter_config.update(t)

    handler_name_list = [t.get_formatter_name() for t in handlers]
    dict_config = {
        'version': 1,
        'disable_existing_loggers': disable_existing_loggers,
        'formatters': new_formatter_config,
        'handlers': new_handlers_config,
        'loggers': {
            '': {
                'handlers': handler_name_list,
                'level': 'DEBUG',
            }
        }
    }

    logging.config.dictConfig(dict_config)
1275589
def init_auditlog(portal):
    
    # reindex the auditlog folder to display the icon right in the setup
    portal.bika_setup.auditlog.reindexObject()

    # Initialize contents for audit logging
    start = time.time()
    uid_catalog = api.get_tool("uid_catalog")
    brains = uid_catalog()
    total = len(brains)

    logger.info("Initializing {} objects for the audit trail...".format(total))
    for num, brain in enumerate(brains):
        # Progress notification
        if num and num % 1000 == 0:
            transaction.commit()
            logger.info("{}/{} ojects initialized for audit logging"
                        .format(num, total))
        # End progress notification
        if num + 1 == total:
            end = time.time()
            duration = float(end-start)
            logger.info("{} ojects initialized for audit logging in {:.2f}s"
                        .format(total, duration))

        if api.get_portal_type(brain) in SKIP_TYPES_FOR_AUDIT_LOG:
            continue

        obj = api.get_object(brain)

        if not supports_snapshots(obj):
            continue

        if has_snapshots(obj):
            continue

        # Take one snapshot per review history item
        rh = api.get_review_history(obj, rev=False)
        for item in rh:
            actor = item.get("actor")
            user = get_user(actor)
            if user:
                # remember the roles of the actor
                item["roles"] = get_roles(user)
            # The review history contains the variable "time" which we will set
            # as the "modification" time
            timestamp = item.pop("time", DateTime())
            item["time"] = timestamp.ISO()
            item["modified"] = timestamp.ISO()
            item["remote_address"] = None
            take_snapshot(obj, **item)