[libcamera-devel] [PATCH] libcamera: log: add colors to log levels

Marco Felsch m.felsch at pengutronix.de
Wed May 5 17:33:18 CEST 2021


Add colored logs if the output belongs to a terminal. This makes it easier
to identitify warnings and/or errors.

Signed-off-by: Marco Felsch <m.felsch at pengutronix.de>
---
Hi all,

this is an reworked version of [1]. I used by sob and auther since I did
more changes than I kept from [1].

[1] 20210203181746.22028-1-m.cichy at pengutronix.de

 src/libcamera/log.cpp | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)

diff --git a/src/libcamera/log.cpp b/src/libcamera/log.cpp
index 94175ab3..3dffd004 100644
--- a/src/libcamera/log.cpp
+++ b/src/libcamera/log.cpp
@@ -19,6 +19,7 @@
 #include <string.h>
 #include <syslog.h>
 #include <time.h>
+#include <unistd.h>
 #include <unordered_set>
 
 #include <libcamera/logging.h>
@@ -98,6 +99,26 @@ static const char *log_severity_name(LogSeverity severity)
 		return "UNKWN";
 }
 
+static const char *log_severity_color_name(LogSeverity severity)
+{
+	static const char *const names[] = {
+		"\033[1m\033[37mDEBUG\033[0m",
+		"\033[1m\033[32m INFO\033[0m",
+		"\033[1m\033[33m WARN\033[0m",
+		"\033[1m\033[31mERROR\033[0m",
+		"\033[1m\033[35mFATAL\033[0m",
+	};
+
+	/* Only print colored output if output really belongs to a terminal */
+	if (!isatty(fileno(stderr)))
+		return log_severity_name(severity);
+
+	if (static_cast<unsigned int>(severity) < std::size(names))
+		return names[severity];
+	else
+		return "\033[1m\033[32mUNKWN\033[0m";
+}
+
 /**
  * \brief Log output
  *
@@ -197,6 +218,13 @@ void LogOutput::write(const LogMessage &msg)
 		writeSyslog(msg.severity(), str);
 		break;
 	case LoggingTargetStream:
+		str = "[" + utils::time_point_to_string(msg.timestamp()) + "] ["
+		    + std::to_string(Thread::currentId()) + "] "
+		    + log_severity_color_name(msg.severity()) + " "
+		    + msg.category().name() + " " + msg.fileInfo() + " "
+		    + msg.msg();
+		writeStream(str);
+		break;
 	case LoggingTargetFile:
 		str = "[" + utils::time_point_to_string(msg.timestamp()) + "] ["
 		    + std::to_string(Thread::currentId()) + "] "
-- 
2.29.2



More information about the libcamera-devel mailing list