From 9b1f36d274459d12866abb1da47d8fe891131650 Mon Sep 17 00:00:00 2001 From: Tatsuhiro Tsujikawa Date: Sun, 9 Dec 2012 21:02:48 +0900 Subject: [PATCH] shrpx: Color severity level in terminal Color severity level if stderr refers to a terminal. --- src/shrpx.cc | 1 + src/shrpx_config.h | 2 ++ src/shrpx_log.cc | 24 ++++++++++++++++++++---- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/shrpx.cc b/src/shrpx.cc index 202da17..2575878 100644 --- a/src/shrpx.cc +++ b/src/shrpx.cc @@ -369,6 +369,7 @@ void fill_default_config() mod_config()->gid = 0; mod_config()->backend_ipv4 = false; mod_config()->backend_ipv6 = false; + mod_config()->tty = isatty(fileno(stderr)); } } // namespace diff --git a/src/shrpx_config.h b/src/shrpx_config.h index 4301d25..ca03f20 100644 --- a/src/shrpx_config.h +++ b/src/shrpx_config.h @@ -122,6 +122,8 @@ struct Config { char *cacert; bool backend_ipv4; bool backend_ipv6; + // true if stderr refers to a terminal. + bool tty; }; const Config* get_config(); diff --git a/src/shrpx_log.cc b/src/shrpx_log.cc index 2ab9f0d..b9961fc 100644 --- a/src/shrpx_log.cc +++ b/src/shrpx_log.cc @@ -33,9 +33,20 @@ namespace shrpx { +namespace { const char *SEVERITY_STR[] = { "INFO", "WARN", "ERROR", "FATAL" }; +} // namespace + +namespace { +const char *SEVERITY_COLOR[] = { + "\033[1;32m", // INFO + "\033[1;33m", // WARN + "\033[1;31m", // ERROR + "\033[1;35m", // FATAL +}; +} // namespace int Log::severity_thres_ = WARNING; @@ -80,12 +91,17 @@ Log::Log(int severity, const char *filename, int linenum) Log::~Log() { if(severity_ >= severity_thres_) { - fprintf(stderr, "[%s] %s\n (%s, line %d)\n", - SEVERITY_STR[severity_], stream_.str().c_str(), - filename_, linenum_); + fprintf(stderr, "[%s%s%s] %s\n %s(%s:%d)%s\n", + get_config()->tty ? SEVERITY_COLOR[severity_] : "", + SEVERITY_STR[severity_], + get_config()->tty ? "\033[0m" : "", + stream_.str().c_str(), + get_config()->tty ? "\033[1;30m" : "", + filename_, linenum_, + get_config()->tty ? "\033[0m" : ""); fflush(stderr); if(get_config()->use_syslog) { - syslog(severity_to_syslog_level(severity_), "%s (%s, line %d)\n", + syslog(severity_to_syslog_level(severity_), "%s (%s:%d)\n", stream_.str().c_str(), filename_, linenum_); } }