From 6ecbc1c1c5eac92fce40bc931ffb953f1d7a5d1d Mon Sep 17 00:00:00 2001 From: Chris Wilson Date: Sun, 22 Apr 2007 14:23:24 +0000 Subject: Add options to log timestamps, and a custom tag, with each message to the console, e.g.: 14:53:17 [bbackupd] Finished scan of local files (refs #3) --- lib/common/Logging.cpp | 56 +++++++++++++++++++++++++++++++++++++++++++++++++- lib/common/Logging.h | 8 ++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) (limited to 'lib/common') diff --git a/lib/common/Logging.cpp b/lib/common/Logging.cpp index 5ecadc72..4078a679 100644 --- a/lib/common/Logging.cpp +++ b/lib/common/Logging.cpp @@ -9,12 +9,16 @@ #include "Box.h" +#include + #ifdef HAVE_SYSLOG_H #include #endif #include "Logging.h" +#include + bool Logging::sLogToSyslog = false; bool Logging::sLogToConsole = false; bool Logging::sContextSet = false; @@ -172,6 +176,21 @@ Logger::~Logger() Logging::Remove(this); } +bool Console::sShowTime = false; +bool Console::sShowTag = false; +std::string Console::sTag; + +void Console::SetTag(const std::string& rTag) +{ + sTag = rTag; + sShowTag = true; +} + +void Console::SetShowTime(bool enabled) +{ + sShowTime = enabled; +} + bool Console::Log(Log::Level level, const std::string& rFile, int line, std::string& rMessage) { @@ -186,8 +205,43 @@ bool Console::Log(Log::Level level, const std::string& rFile, { target = stderr; } + + std::string msg; + + if (sShowTime) + { + struct tm time_now; + time_t time_t_now = time(NULL); + + if (time_t_now == ((time_t)-1)) + { + msg += strerror(errno); + msg += " "; + } + else if (localtime_r(&time_t_now, &time_now) != NULL) + { + std::ostringstream buf; + buf << std::setfill('0') << + std::setw(2) << time_now.tm_hour << ":" << + std::setw(2) << time_now.tm_min << ":" << + std::setw(2) << time_now.tm_sec << " "; + msg += buf.str(); + } + else + { + msg += strerror(errno); + msg += " "; + } + } + + if (sShowTag) + { + msg += "[" + sTag + "] "; + } - fprintf(target, "%s\n", rMessage.c_str()); + msg += rMessage; + + fprintf(target, "%s\n", msg.c_str()); return true; } diff --git a/lib/common/Logging.h b/lib/common/Logging.h index 04aed1cf..65018632 100644 --- a/lib/common/Logging.h +++ b/lib/common/Logging.h @@ -102,11 +102,19 @@ class Logger class Console : public Logger { + private: + static bool sShowTime; + static bool sShowTag; + static std::string sTag; + public: virtual bool Log(Log::Level level, const std::string& rFile, int line, std::string& rMessage); virtual const char* GetType() { return "Console"; } virtual void SetProgramName(const std::string& rProgramName) { } + + static void SetTag(const std::string& rTag); + static void SetShowTime(bool enabled); }; // -------------------------------------------------------------------------- -- cgit v1.2.3