001package io.prometheus.metrics.expositionformats; 002 003import io.prometheus.metrics.model.snapshots.Labels; 004import java.io.IOException; 005import java.io.OutputStreamWriter; 006import java.io.Writer; 007 008public class TextFormatUtil { 009 010 static void writeLong(OutputStreamWriter writer, long value) throws IOException { 011 writer.append(Long.toString(value)); 012 } 013 014 static void writeDouble(OutputStreamWriter writer, double d) throws IOException { 015 if (d == Double.POSITIVE_INFINITY) { 016 writer.write("+Inf"); 017 } else if (d == Double.NEGATIVE_INFINITY) { 018 writer.write("-Inf"); 019 } else { 020 writer.write(Double.toString(d)); 021 // FloatingDecimal.getBinaryToASCIIConverter(d).appendTo(writer); 022 } 023 } 024 025 static void writeTimestamp(OutputStreamWriter writer, long timestampMs) throws IOException { 026 writer.write(Long.toString(timestampMs / 1000L)); 027 writer.write("."); 028 long ms = timestampMs % 1000; 029 if (ms < 100) { 030 writer.write("0"); 031 } 032 if (ms < 10) { 033 writer.write("0"); 034 } 035 writer.write(Long.toString(ms)); 036 } 037 038 static void writeEscapedLabelValue(Writer writer, String s) throws IOException { 039 for (int i = 0; i < s.length(); i++) { 040 char c = s.charAt(i); 041 switch (c) { 042 case '\\': 043 writer.append("\\\\"); 044 break; 045 case '\"': 046 writer.append("\\\""); 047 break; 048 case '\n': 049 writer.append("\\n"); 050 break; 051 default: 052 writer.append(c); 053 } 054 } 055 } 056 057 static void writeLabels( 058 OutputStreamWriter writer, 059 Labels labels, 060 String additionalLabelName, 061 double additionalLabelValue) 062 throws IOException { 063 writer.write('{'); 064 for (int i = 0; i < labels.size(); i++) { 065 if (i > 0) { 066 writer.write(","); 067 } 068 writer.write(labels.getPrometheusName(i)); 069 writer.write("=\""); 070 writeEscapedLabelValue(writer, labels.getValue(i)); 071 writer.write("\""); 072 } 073 if (additionalLabelName != null) { 074 if (!labels.isEmpty()) { 075 writer.write(","); 076 } 077 writer.write(additionalLabelName); 078 writer.write("=\""); 079 writeDouble(writer, additionalLabelValue); 080 writer.write("\""); 081 } 082 writer.write('}'); 083 } 084}