[sheepdog] [PATCH RFC 2/3] logger: json format for logging

Hitoshi Mitake mitake.hitoshi at lab.ntt.co.jp
Mon Jan 28 12:15:25 CET 2013


This patch implements a function for formatting logs in json.

Signed-off-by: Hitoshi Mitake <mitake.hitoshi at lab.ntt.co.jp>
---
 lib/logger.c |   51 +++++++++++++++++++++++++++++++++++++++++++++++++--
 1 files changed, 49 insertions(+), 2 deletions(-)

diff --git a/lib/logger.c b/lib/logger.c
index 2dc7ce1..54464ad 100644
--- a/lib/logger.c
+++ b/lib/logger.c
@@ -183,14 +183,61 @@ static notrace int default_log_format(char *buff, size_t size,
 	return p - buff;
 }
 
+static notrace int json_log_format(char *buff, size_t size,
+				const struct logmsg *msg)
+{
+	int i, body_len;
+	char *p = buff;
+
+	snprintf(p, size, "{");
+	p += strlen(p);
+
+	snprintf(p, size - strlen(buff), "\"time\": \"%lu\"", msg->t);
+	p += strlen(p);
+
+	if (strlen(msg->worker_name))
+		snprintf(p, size - strlen(buff), ", \"worker_name\": \"%s\"",
+			msg->worker_name);
+	else
+		snprintf(p, size - strlen(buff), ", \"worker_name\": \"main\"");
+
+	p += strlen(p);
+
+	snprintf(p, size - strlen(buff), ", \"worker_idx\": %d",
+		msg->worker_idx);
+	p += strlen(p);
+
+	snprintf(p, size - strlen(buff), ", \"func\": \"%s\"", msg->func);
+	p += strlen(p);
+
+	snprintf(p, size - strlen(buff), ", \"line\": %d", msg->line);
+	p += strlen(p);
+
+	snprintf(p, size - strlen(buff), ", \"body\": \"");
+	p += strlen(p);
+
+	body_len = strlen(msg->str) - 1;
+	/* this - 1 eliminates '\n', dirty... */
+	for (i = 0; i < body_len; i++) {
+		if (msg->str[i] == '"')
+			*p++ = '\\';
+		*p++ = msg->str[i];
+	}
+
+	snprintf(p, size - strlen(buff), "\"}\n");
+	p += strlen(p);
+
+	return p - buff;
+}
+
 /*
  * this one can block under memory pressure
  */
 static notrace void log_syslog(const struct logmsg *msg)
 {
-	char str[MAX_MSG_SIZE];
+	char str[MAX_MSG_SIZE * 2];
 
-	memset(str, 0, MAX_MSG_SIZE);
+	memset(str, 0, MAX_MSG_SIZE * 2);
 	default_log_format(str, MAX_MSG_SIZE, msg);
 	if (log_fd >= 0)
 		xwrite(log_fd, str, strlen(str));
-- 
1.7.2.5




More information about the sheepdog mailing list