[Pcsclite-cvs-commit] CVS PCSC/src

CVS User rousseau ludovic.rousseau@free.fr
Thu, 17 Mar 2005 01:22:19 -0700


Update of /cvsroot/pcsclite/PCSC/src
In directory haydn:/tmp/cvs-serv19311

Modified Files:
	debuglog.c 
Log Message:
add colorization of the logs when sent to stderr. The color depends on
the priority level:
- critical: bright red
- error: magenta
- info: blue
- debug: black

A correct implementation should use ncurses to be portable but I don't
want to add a dependency on pcscd.

The code and idea is greatly inspired from OpenSC.


--- /cvsroot/pcsclite/PCSC/src/debuglog.c	2005/03/17 07:53:53	1.37
+++ /cvsroot/pcsclite/PCSC/src/debuglog.c	2005/03/17 08:22:19	1.38
@@ -8,7 +8,7 @@
  * Copyright (C) 1999-2005
  *  Ludovic Rousseau <ludovic.rousseau@free.fr>
  *
- * $Id: debuglog.c,v 1.37 2005/03/17 07:53:53 rousseau Exp $
+ * $Id: debuglog.c,v 1.38 2005/03/17 08:22:19 rousseau Exp $
  */
 
 #include "config.h"
@@ -39,6 +39,8 @@
 /* default level is a bit verbose to be backward compatible */
 static char LogLevel = PCSC_LOG_INFO;
 
+static char LogDoColor = -1;	/* not initialised */
+
 void log_msg(const int priority, const char *fmt, ...)
 {
 	char DebugBuffer[DEBUG_BUF_SIZE];
@@ -49,6 +51,40 @@
 		|| (DEBUGLOG_NO_DEBUG == LogMsgType))
 		return;
 
+	/* color not yet initialised? */
+	if (-1 == LogDoColor)
+	{
+		LogDoColor = 0;	/* no color by default */
+
+		/* no color under Windows */
+#ifndef WIN32
+
+		/* log to stderr and stderr is a tty? */
+		if (DEBUGLOG_STDERR_DEBUG == LogMsgType && isatty(fileno(stderr)))
+		{
+			const char *terms[] = { "linux", "xterm", "Eterm", "rxvt" };
+			char *term;
+
+			term = getenv("TERM");
+			if (term)
+			{
+				int i;
+
+				/* for each known color terminal */
+				for (i = 0; i < sizeof(terms) / sizeof(terms[0]); i++)
+				{
+					/* we found a supported term? */
+					if (0 == strcmp(terms[i], term))
+					{
+						LogDoColor = 1;
+						break;
+					}
+				}
+			}
+		}
+#endif
+	}
+
 	va_start(argptr, fmt);
 #ifndef WIN32
 	vsnprintf(DebugBuffer, DEBUG_BUF_SIZE, fmt, argptr);
@@ -65,8 +101,38 @@
 	if (DEBUGLOG_SYSLOG_DEBUG == LogMsgType)
 		syslog(LOG_INFO, "%s", DebugBuffer);
 	else
+	{
+		if (LogDoColor)
+		{
+			const char *color_pfx = "", *color_sfx = "\33[0m";
+
+			switch (priority)
+			{
+				case PCSC_LOG_CRITICAL:
+					color_pfx = "\33[01;31m"; /* bright + Red */
+					break;
+
+				case PCSC_LOG_ERROR:
+					color_pfx = "\33[35m"; /* Magenta */
+					break;
+
+				case PCSC_LOG_INFO:
+					color_pfx = "\33[34m"; /* Blue */
+					break;
+
+				case PCSC_LOG_DEBUG:
+					color_pfx = ""; /* normal (black) */
+					color_sfx = "";
+					break;
+			}
+			fprintf(stderr, "%s%s%s\n", color_pfx, DebugBuffer, color_sfx);
+		}
+		else
+			fprintf(stderr, "%s\n", DebugBuffer);
+	}
+#else
+	fprintf(stderr, "%s\n", DebugBuffer);
 #endif
-		fprintf(stderr, "%s\n", DebugBuffer);
 } /* log_msg */
 
 void log_xxd(const int priority, const char *msg, const unsigned char *buffer,