[PATCH iproute2-next v2 2/3] utils: timestamp: add JSON support

Matthieu Baerts (NGI0) posted 3 patches 6 days, 15 hours ago
[PATCH iproute2-next v2 2/3] utils: timestamp: add JSON support
Posted by Matthieu Baerts (NGI0) 6 days, 15 hours ago
Supporting JSON is easy with the helpers. The biggest modification is to
extract the end value. Different keys are used depending on the short or
long timestamp option being used, to ease the parsing.

No behavioural changes intended for the moment, this is a preparation for a
future usage of print_timestamp() within a JSON context.

Like in other helpers supporting JSON, the output stream 'fp' is ignored,
which is fine, because it is always set to 'stdout'.

Signed-off-by: Matthieu Baerts (NGI0) <matttbe@kernel.org>
---
v2: ignore 'fp' which is always set to 'stdout' (Stephen)
---
 lib/utils.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/lib/utils.c b/lib/utils.c
index 13e8c098..1215fe31 100644
--- a/lib/utils.c
+++ b/lib/utils.c
@@ -1277,21 +1277,23 @@ int print_timestamp(FILE *fp)
 {
 	struct timeval tv;
 	struct tm *tm;
+	char ts[40];
 
 	gettimeofday(&tv, NULL);
 	tm = localtime(&tv.tv_sec);
 
 	if (timestamp_short) {
-		char tshort[40];
+		size_t len;
 
-		strftime(tshort, sizeof(tshort), "%Y-%m-%dT%H:%M:%S", tm);
-		fprintf(fp, "[%s.%06ld] ", tshort, tv.tv_usec);
+		len = strftime(ts, sizeof(ts), "%Y-%m-%dT%H:%M:%S", tm);
+		snprintf(ts + len, sizeof(ts) - len, ".%06ld", tv.tv_usec);
+		print_string(PRINT_ANY, "timestamp_short", "[%s] ", ts);
 	} else {
 		char *tstr = asctime(tm);
 
 		tstr[strlen(tstr)-1] = 0;
-		fprintf(fp, "Timestamp: %s %ld usec\n",
-			tstr, tv.tv_usec);
+		snprintf(ts, sizeof(ts), "%s %ld usec", tstr, tv.tv_usec);
+		print_string(PRINT_ANY, "timestamp", "Timestamp: %s\n", ts);
 	}
 
 	return 0;

-- 
2.51.0