Colored kernel messages on serial console

Timo Buhrmester <[email protected]> Mon, 27 Jul 2026 18:55:41 +0200
Newsgroups gmane.os.netbsd.devel.kernel
Message-ID <[email protected]>
Without *really* knowing what I'm doing, I've just changed the kprintf
to produce ANSI color sequences so that I'll get my familiar green
kernel messages (after migrating from wscons to a serial console setup
recently).

How insane is this?  It seems to work fine, but like I said, I'm not
really familiar with the code.  And would NetBSD be interested in this,
if it was implemented cleanly (i.e. color being configurable, etc.)?

(I realize it still needs something to stop it if the console is, say,
wscons.  I figured a sysctl might be an okay choice, but if there is
maybe a more automatic way to tell what console actually is...?)

I'd appreciate any input.

Cheers
Timo

------8<-----------------------------

diff --git a/sys/kern/subr_prf.c b/sys/kern/subr_prf.c
index f634e4392..79de072bd 100644
--- a/sys/kern/subr_prf.c
+++ b/sys/kern/subr_prf.c
@@ -1277,6 +1277,15 @@ kprintf(const char *fmt0, int oflags, void *vp, char *sbuf, va_list ap)
 	else
 		tailp = NULL;
 
+	#define COL_GN "\033[32;1m"
+	#define COL_RST "\033[0m"
+
+	if (oflags & TOCONS) {
+		const char *colp = COL_GN;
+		while (*colp)
+			putchar(*colp++, TOCONS|NOTSTAMP, vp); 
+	}
+
 	cp = NULL;	/* XXX: shutup gcc */
 	size = 0;	/* XXX: shutup gcc */
 
@@ -1618,6 +1627,12 @@ number:			if ((dprec = prec) >= 0)
 done:
 	if ((oflags == TOBUFONLY) && (vp != NULL))
 		*(char **)vp = sbuf;
+	if (oflags & TOCONS) {
+		const char *colp = COL_RST;
+		while (*colp)
+			putchar(*colp++, TOCONS|NOTSTAMP, vp); 
+	}
+
 	(*v_flush)();
 
 #ifdef RND_PRINTF