set whether or not to generate "pretty formatted" JSON in trace-logging
769417
public void setTracePrettyPrint(boolean pretty) {
        if (this.httpClient instanceof DefaultHttpClient) {
            ((DefaultHttpClient)this.httpClient).setTracePrettyPrint(pretty);
        }
        else
            throw new UnsupportedOperationException("Invalid operation for class " + this.httpClient.getClass());
    }
711429
def make_json_formatter(graph):
    

    return {
        "()": graph.config.logging.json_formatter.formatter,
        "fmt": graph.config.logging.json_required_keys,
    }
410305
@Override
    public void trace(String format, Object arg) {
        if (logger.isTraceEnabled()) {
            FormattingTuple ft = MessageFormatter.format(format, arg);
            logger.trace(ft.getMessage(), ft.getThrowable());
        }
    }
892797
def paste_traceback(self, request, traceback):
        """"""
        rv = traceback.paste()
        return Response(json.dumps(rv), content_type='application/json')
296279
def format_logstash_v0(self, record):
        '''
        
        '''
        host = salt.utils.network.get_fqhostname()
        message_dict = {
            '@timestamp': self.formatTime(record),
            '@fields': {
                'levelname': record.levelname,
                'logger': record.name,
                'lineno': record.lineno,
                'pathname': record.pathname,
                'process': record.process,
                'threadName': record.threadName,
                'funcName': record.funcName,
                'processName': record.processName
            },
            '@message': record.getMessage(),
            '@source': '{0}://{1}/{2}'.format(
                self.msg_type,
                host,
                self.msg_path
            ),
            '@source_host': host,
            '@source_path': self.msg_path,
            '@tags': self.tags,
            '@type': self.msg_type,
        }

        if record.exc_info:
            message_dict['@fields']['exc_info'] = self.formatException(
                record.exc_info
            )

        # Add any extra attributes to the message field
        for key, value in six.iteritems(record.__dict__):
            if key in ('args', 'asctime', 'created', 'exc_info', 'exc_text',
                       'filename', 'funcName', 'id', 'levelname', 'levelno',
                       'lineno', 'module', 'msecs', 'msecs', 'message', 'msg',
                       'name', 'pathname', 'process', 'processName',
                       'relativeCreated', 'thread', 'threadName'):
                # These are already handled above or not handled at all
                continue

            if value is None:
                message_dict['@fields'][key] = value
                continue

            if isinstance(value, (six.string_types, bool, dict, float, int, list)):
                message_dict['@fields'][key] = value
                continue

            message_dict['@fields'][key] = repr(value)
        return message_dict
855918
function prettyPrintJson(obj, indent) {
  var result = '';

  if (indent == null) indent = '';

  for (var property in obj) {
    if (property.charAt(0) !== '_') {
      var value = obj[property];

      if (typeof value === 'string') {
        value = '\'' + value + '\'';
      } else if (typeof value === 'object') {
        if (value instanceof Array) {
          value = '[ ' + value + ' ]';
        } else {
          // Recursive dump
          var od = prettyPrintJson(value, indent + '  ');

          value = '{\n' + od + '\n' + indent + '}';
        }
      }
      result += indent + property + ': ' + value + ',\n';
    }
  }
  return result.replace(/,\n$/, '');
}
363945
def log_trace(self, tag, original, loc, tokens=None, extra=None):
        """"""
        if self.tracing:
            tag, original, loc = displayable(tag), displayable(original), int(loc)
            if "{" not in tag:
                out = ["[" + tag + "]"]
                add_line_col = True
                if tokens is not None:
                    if isinstance(tokens, Exception):
                        msg = displayable(str(tokens))
                        if "{" in msg:
                            head, middle = msg.split("{", 1)
                            middle, tail = middle.rsplit("}", 1)
                            msg = head + "{...}" + tail
                        out.append(msg)
                        add_line_col = False
                    elif len(tokens) == 1 and isinstance(tokens[0], str):
                        out.append(ascii(tokens[0]))
                    else:
                        out.append(ascii(tokens))
                if add_line_col:
                    out.append("(line:" + str(lineno(loc, original)) + ", col:" + str(col(loc, original)) + ")")
                if extra is not None:
                    out.append("from " + ascii(extra))
                printerr(*out)
771921
def dump_json(data, indent=None):
    
    return json.dumps(data,
                      indent=indent,
                      ensure_ascii=False,
                      sort_keys=True,
                      separators=(',', ': '))
1085242
def _format_json(data, theme):
    """"""
    output = json.dumps(data, indent=2, sort_keys=True)

    if pygments and sys.stdout.isatty():
        style = get_style_by_name(theme)
        formatter = Terminal256Formatter(style=style)
        return pygments.highlight(output, JsonLexer(), formatter)

    return output
175667
def json(value, pretty=True):
    
    if not _Duration:
        _late_import()
    return _json_encoder(value, pretty=pretty)
15720
def pretty_json(obj):
    
    if isinstance(obj, string_types):
        try:
            obj = json.loads(obj)
        except ValueError:
            raise ClientException("`obj` is not a json string")
    json_str = json.dumps(obj, sort_keys=True, indent=2)
    print(highlight(json_str, JsonLexer(), TerminalFormatter()))
1159235
def format_json(event, colored):
        

        try:
            if event.message.startswith("{"):
                msg_dict = json.loads(event.message)
                event.message = json.dumps(msg_dict, indent=2)
        except Exception:
            # Skip if the event message was not JSON
            pass

        return event
131204
def format(self, record):
        """"""
        message_dict = {}
        if isinstance(record.msg, dict):
            message_dict = record.msg
            record.message = None
        else:
            record.message = record.getMessage()
        # only format time if needed
        if "asctime" in self._required_fields:
            record.asctime = self.formatTime(record, self.datefmt)

        # Display formatted exception, but allow overriding it in the
        # user-supplied dict.
        if record.exc_info and not message_dict.get('exc_info'):
            message_dict['exc_info'] = self.formatException(record.exc_info)
        if not message_dict.get('exc_info') and record.exc_text:
            message_dict['exc_info'] = record.exc_text
        # Display formatted record of stack frames
        # default format is a string returned from :func:`traceback.print_stack`
        try:
            if record.stack_info and not message_dict.get('stack_info'):
                message_dict['stack_info'] = self.formatStack(record.stack_info)
        except AttributeError:
            # Python2.7 doesn't have stack_info.
            pass

        try:
            log_record = OrderedDict()
        except NameError:
            log_record = {}

        self.add_fields(log_record, record, message_dict)
        log_record = self.process_log_record(log_record)

        return "%s%s" % (self.prefix, self.jsonify_log_record(log_record))
57352
def outformat_is_json():
    
    ctx = click.get_current_context()
    state = ctx.ensure_object(CommandState)
    return state.outformat_is_json()
916468
def echo_json_response(response, pretty, limit=None, ndjson=False):
    ''''''
    indent = None
    sort_keys = False
    nl = False
    if not ndjson and (pretty or (pretty is None and sys.stdout.isatty())):
        indent = 2
        sort_keys = True
        nl = True
    try:
        if ndjson and hasattr(response, 'items_iter'):
            items = response.items_iter(limit)
            for item in items:
                click.echo(json.dumps(item))
        elif not ndjson and hasattr(response, 'json_encode'):
            response.json_encode(click.get_text_stream('stdout'), limit=limit,
                                 indent=indent, sort_keys=sort_keys)
        else:
            res = response.get_raw()
            res = json.dumps(json.loads(res), indent=indent,
                             sort_keys=sort_keys)
            click.echo(res)
        if nl:
            click.echo()
    except IOError as ioe:
        # hide scary looking broken pipe stack traces
        raise click.ClickException(str(ioe))
936486
def log_path(scraper):
    
    return os.path.join(scraper.config.data_path,
                        '%s.jsonlog' % scraper.name)
299789
public static String prettyPrint(String unformattedJsonString) {
        StringBuilder sb = new StringBuilder();
        int indentLevel = 0;
        boolean inQuote = false;
        for (char charFromUnformattedJson : unformattedJsonString.toCharArray()) {
            switch (charFromUnformattedJson) {
                case '"':
                    // switch the quoting status
                    inQuote = !inQuote;
                    sb.append(charFromUnformattedJson);
                    break;
                case ' ':
                    // For space: ignore the space if it is not being quoted.
                    if (inQuote) {
                        sb.append(charFromUnformattedJson);
                    }
                    break;
                case '{':
                case '[':
                    // Starting a new block: increase the indent level
                    sb.append(charFromUnformattedJson);
                    indentLevel++;
                    appendIndentedNewLine(indentLevel, sb);
                    break;
                case '}':
                case ']':
                    // Ending a new block; decrese the indent level
                    indentLevel--;
                    appendIndentedNewLine(indentLevel, sb);
                    sb.append(charFromUnformattedJson);
                    break;
                case ',':
                    // Ending a json item; create a new line after
                    sb.append(charFromUnformattedJson);
                    if (!inQuote) {
                        appendIndentedNewLine(indentLevel, sb);
                    }
                    break;
                default:
                    sb.append(charFromUnformattedJson);
            }
        }
        return sb.toString();
    }