Formats a log message which contains placeholders (i.e. when a template context exists). This
does not format only metadata, only the message and its arguments.
518417
private static StringBuilder formatMessage(LogData logData) {
    SimpleMessageFormatter formatter =
        new SimpleMessageFormatter(logData.getTemplateContext(), logData.getArguments());
    StringBuilder out = formatter.build();
    if (logData.getArguments().length > formatter.getExpectedArgumentCount()) {
      // TODO(dbeaumont): Do better and look at adding formatted values or maybe just a count?
      out.append(EXTRA_ARGUMENT_MESSAGE);
    }
    return out;
  }
1256518
private static void formatBadLogData(LogData data, StringBuilder out) {
    out.append("  original message: ");
    if (data.getTemplateContext() == null) {
      out.append(data.getLiteralArgument());
    } else {
      // We know that there's at least one argument to display here.
      out.append(data.getTemplateContext().getMessage());
      out.append("\n  original arguments:");
      for (Object arg : data.getArguments()) {
        out.append("\n    ").append(SimpleMessageFormatter.safeToString(arg));
      }
    }
    Metadata metadata = data.getMetadata();
    if (metadata.size() > 0) {
      out.append("\n  metadata:");
      for (int n = 0; n < metadata.size(); n++) {
        out.append("\n    ");
        out.append(metadata.getKey(n).getLabel()).append(": ").append(metadata.getValue(n));
      }
    }
    out.append("\n  level: ").append(data.getLevel());
    out.append("\n  timestamp (nanos): ").append(data.getTimestampNanos());
    out.append("\n  class: ").append(data.getLogSite().getClassName());
    out.append("\n  method: ").append(data.getLogSite().getMethodName());
    out.append("\n  line number: ").append(data.getLogSite().getLineNumber());
  }
984579
public String formatMessage(String key, Object[] args) {
		try {
			String raw = this.getMessage(key);
			return MessageFormat.format(raw, args);
		} catch (MissingResourceException ex) {
			return "???!"+key+"!???";
		}
	}
367395
@Override
  public String format(LogRecord log)
  {
    StringBuilder sb = new StringBuilder();
    
    int mark = 0;

    for (FormatItem item : _formatList) {
      item.format(sb, log, mark);
      
      if (item instanceof PrettyPrintMarkItem) {
        mark = sb.length();
      }
    }
    
    return sb.toString();
  }
676210
@Override
	public String formatLogMsg(LogEvent logEvent) {
		LogMessageType      messageInfo  = logEvent.getLogEntry().getMessageInfo();
		LogMetadataInfoType metadataInfo = logEvent.getLogEntry().getMetadataInfo();
		LogRuntimeInfoType  runtimeInfo  = logEvent.getLogEntry().getRuntimeInfo();

		String integrationScenarioId   = metadataInfo.getIntegrationScenarioId();
		String contractId              = metadataInfo.getContractId();
		String logMessage              = messageInfo.getMessage();
		String serviceImplementation   = metadataInfo.getServiceImplementation();
		String componentId             = runtimeInfo.getComponentId();
		String endpoint                = metadataInfo.getEndpoint();
		String messageId               = runtimeInfo.getMessageId();
		String businessCorrelationId   = runtimeInfo.getBusinessCorrelationId();
		String payload                 = logEvent.getLogEntry().getPayload();
		String businessContextIdString = businessContextIdToString(runtimeInfo.getBusinessContextId());
		String extraInfoString         = extraInfoToString(logEvent.getLogEntry().getExtraInfo());
		String logEventName            = "logEvent-" + messageInfo.getLevel().toString().toLowerCase();

		StringBuffer stackTrace = new StringBuffer();
		LogMessageExceptionType lmeException = logEvent.getLogEntry().getMessageInfo().getException();
		if (lmeException != null) {
			String ex = lmeException.getExceptionClass();
			String msg = lmeException.getExceptionMessage();
			List<String> st = lmeException.getStackTrace();

			stackTrace.append('\n').append("Stacktrace=").append(ex).append(": ").append(msg);
			for (String stLine : st) {
				if (stLine.startsWith(CAUSE_EXCEPTION_HEADER)) {
					stackTrace.append("\n\n").append(stLine);
					
				} else {
					stackTrace.append("\n\t at ").append(stLine);
				}
			}
		}
		return MessageFormatter.arrayFormat(LOG_STRING, new String[] {logEventName, integrationScenarioId, contractId, logMessage, serviceImplementation, runtimeInfo.getHostName(), runtimeInfo.getHostIp(), componentId, endpoint, messageId, businessCorrelationId, businessContextIdString, extraInfoString, payload, stackTrace.toString(), logEventName}).getMessage();
	}
617624
def format( event )
      obj = format_obj(event.data)
      sprintf("%*s  %s : %s\n", ::Logsly::Logging182::MAX_LEVEL_LENGTH,
              ::Logsly::Logging182::LNAMES[event.level], event.logger, obj)
    end
244301
function processMessageNode (message) {
      if (
        (message.type === 'Literal' && typeof message.value === 'string' && !pattern.test(message.value)) ||
        (message.type === 'TemplateLiteral' && message.quasis.length === 1 && !pattern.test(message.quasis[0].value.cooked))
      ) {
        context.report({
          node: message,
          message: "Report message does not match the pattern '{{pattern}}'.",
          data: { pattern: context.options[0] || '' },
        });
      }
    }
1072663
protected String formatMessage(String message, Object[] parameters) {
        String formatted;
        if (printfStyle) {
            formatted = String.format(message, parameters);
        } else {
            formatted = MessageFormat.format(message, parameters);
        }
        return formatted;
    }
687870
def format_check(settings):
    

    valid_keys = ['logs_folder', 'log_file', 'log_console', 'log_name',
                  'log_filename', 'keep_osm_tags']

    for key in list(settings.keys()):
        assert key in valid_keys, \
            ('{} not found in list of valid configuation keys').format(key)
        assert isinstance(key, str), ('{} must be a string').format(key)
        if key == 'keep_osm_tags':
            assert isinstance(settings[key], list), \
                ('{} must be a list').format(key)
            for value in settings[key]:
                assert all(isinstance(element, str) for element in value), \
                    'all elements must be a string'
        if key == 'log_file' or key == 'log_console':
            assert isinstance(settings[key], bool), \
                ('{} must be boolean').format(key)
290942
def _ReformatMessageString(self, message_string):
    
    def _PlaceHolderSpecifierReplacer(match_object):
      """Replaces message string place holders into Python format() style."""
      expanded_groups = []
      for group in match_object.groups():
        try:
          place_holder_number = int(group, 10) - 1
          expanded_group = '{{{0:d}:s}}'.format(place_holder_number)
        except ValueError:
          expanded_group = group

        expanded_groups.append(expanded_group)

      return ''.join(expanded_groups)

    if not message_string:
      return None

    message_string = self._WHITE_SPACE_SPECIFIER_RE.sub(r'', message_string)
    message_string = self._TEXT_SPECIFIER_RE.sub(r'\\\1', message_string)
    message_string = self._CURLY_BRACKETS.sub(r'\1\1', message_string)
    return self._PLACE_HOLDER_SPECIFIER_RE.sub(
        _PlaceHolderSpecifierReplacer, message_string)
146417
def format(self, record):
        
        out = dict(
            Timestamp=int(record.created * 1e9),
            Type=record.name,
            Logger=self.logger_name,
            Hostname=self.hostname,
            EnvVersion=self.LOGGING_FORMAT_VERSION,
            Severity=self.SYSLOG_LEVEL_MAP.get(record.levelno,
                                               self.DEFAULT_SYSLOG_LEVEL),
            Pid=record.process,
        )

        # Include any custom attributes set on the record.
        # These would usually be collected metrics data.
        fields = dict()
        for key, value in record.__dict__.items():
            if key not in self.EXCLUDED_LOGRECORD_ATTRS:
                fields[key] = value

        # Only include the 'message' key if it has useful content
        # and is not already a JSON blob.
        message = record.getMessage()
        if message:
            if not message.startswith("{") and not message.endswith("}"):
                fields["msg"] = message

        # If there is an error, format it for nice output.
        if record.exc_info is not None:
            fields["error"] = repr(record.exc_info[1])
            fields["traceback"] = safer_format_traceback(*record.exc_info)

        out['Fields'] = fields

        return json.dumps(out)
249667
def get_placeholders(self, format_string):
        
        placeholders = set()
        # Tokenize the format string and process them
        for token in self.tokens(format_string):
            if token.group("placeholder"):
                placeholders.add(token.group("key"))
            elif token.group("command"):
                # get any placeholders used in commands
                commands = dict(parse_qsl(token.group("command")))
                # placeholders only used in `if`
                if_ = commands.get("if")
                if if_:
                    placeholders.add(Condition(if_).variable)
        return placeholders
467669
def parse_placeholder(parser, token):
    """"""
    bits = token.split_contents()
    count = len(bits)
    error_string = '%r tag requires at least one argument' % bits[0]
    if count <= 1:
        raise TemplateSyntaxError(error_string)
    name = bits[1]
    remaining = bits[2:]
    params = {}
    simple_options = ['parsed', 'inherited', 'untranslated']
    param_options = ['as', 'on', 'with']
    all_options = simple_options + param_options
    while remaining:
        bit = remaining[0]
        if bit not in all_options:
            raise TemplateSyntaxError(
                "%r is not an correct option for a placeholder" % bit)
        if bit in param_options:
            if len(remaining) < 2:
                raise TemplateSyntaxError(
                "Placeholder option '%s' need a parameter" % bit)
            if bit == 'as':
                params['as_varname'] = remaining[1]
            if bit == 'with':
                params['widget'] = remaining[1]
            if bit == 'on':
                params['page'] = remaining[1]
            remaining = remaining[2:]
        elif bit == 'parsed':
            params['parsed'] = True
            remaining = remaining[1:]
        elif bit == 'inherited':
            params['inherited'] = True
            remaining = remaining[1:]
        elif bit == 'untranslated':
            params['untranslated'] = True
            remaining = remaining[1:]
    return name, params
705872
def update_placeholders(self, format_string, placeholders):
        
        # Tokenize the format string and process them
        output = []
        for token in self.tokens(format_string):
            if token.group("key") in placeholders:
                output.append(
                    "{%s%s}" % (placeholders[token.group("key")], token.group("format"))
                )
                continue
            elif token.group("command"):
                # update any placeholders used in commands
                commands = parse_qsl(token.group("command"), keep_blank_values=True)
                # placeholders only used in `if`
                if "if" in [x[0] for x in commands]:
                    items = []
                    for key, value in commands:
                        if key == "if":
                            # we have to rebuild from the parts we have
                            condition = Condition(value)
                            variable = condition.variable
                            if variable in placeholders:
                                variable = placeholders[variable]
                                # negation via `!`
                                not_ = "!" if not condition.default else ""
                                condition_ = condition.condition or ""
                                # if there is no condition then there is no
                                # value
                                if condition_:
                                    value_ = condition.value
                                else:
                                    value_ = ""
                                value = "{}{}{}{}".format(
                                    not_, variable, condition_, value_
                                )
                        if value:
                            items.append("{}={}".format(key, value))
                        else:
                            items.append(key)

                    # we cannot use urlencode because it will escape things
                    # like `!`
                    output.append(r"\?{} ".format("&".join(items)))
                    continue
            value = token.group(0)
            output.append(value)
        return u"".join(output)
315353
def format(self, record) -> str:
        
        msg = dict(self.formatter_fields_for_record(record))
        if record.flatten and isinstance(record.msg, dict):
            msg.update(record.msg)
        else:
            msg[MSG_FIELDNAME] = record.msg

        if record.extra:
            msg.update(record.extra)
        if record.exc_info:
            msg["exc_info"] = record.exc_info
        if record.exc_text:
            msg["exc_text"] = record.exc_text

        return self.serializer(
            msg, default=self._default_handler, **record.serializer_kwargs
        )
1273705
private String formatMessage(String message, String language, Object... args) {
        if (args != null && args.length > 0) {
            // only format a message if we have arguments
            Locale locale = languages.getLocaleOrDefault(language);
            MessageFormat messageFormat = new MessageFormat(message, locale);
            return messageFormat.format(args);
        }

        return message;
    }
41621
def format(self, record):
        

        fields = record.__dict__.copy()

        if isinstance(record.msg, dict):
            fields.update(record.msg)
            fields.pop('msg')
            msg = ""
        else:
            msg = record.getMessage()

        try:
            msg = msg.format(**fields)
        except (KeyError, IndexError, ValueError):
            pass
        except:
            # in case we can not format the msg properly we log it as is instead of crashing
            msg = msg

        if 'msg' in fields:
            fields.pop('msg')

        if 'exc_info' in fields:
            if fields['exc_info']:
                formatted = tb.format_exception(*fields['exc_info'])
                fields['exception'] = formatted
            fields.pop('exc_info')

        if 'exc_text' in fields and not fields['exc_text']:
            fields.pop('exc_text')

        logr = self.defaults.copy()

        logr.update({'@message': msg,
                     '@timestamp': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
                     '@source_host': self.source_host,
                     '@fields': self._build_fields(logr, fields)})

        return json.dumps(logr, default=self.json_default, cls=self.json_cls)