00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 #include "logger.h"
00022
00023 #include <ctime>
00024 #include <fstream>
00025 #include <iomanip>
00026 #include <iostream>
00027
00028 #ifdef WIN32
00029 #include <windows.h>
00030 #endif
00031
00032 namespace utils
00033 {
00034
00035 static std::ofstream mLogFile;
00036 bool Logger::mHasTimestamp = true;
00037 bool Logger::mTeeMode = false;
00038 Logger::Level Logger::mVerbosity = Logger::INFO;
00045 static std::string getCurrentTime()
00046 {
00047 time_t now;
00048 tm local;
00049
00050
00051 time(&now);
00052
00053
00054
00055 local = *(localtime(&now));
00056
00057
00058 using namespace std;
00059 ostringstream os;
00060 os << "[" << setw(2) << setfill('0') << local.tm_hour
00061 << ":" << setw(2) << setfill('0') << local.tm_min
00062 << ":" << setw(2) << setfill('0') << local.tm_sec
00063 << "]";
00064
00065 return os.str();
00066 }
00067
00068 void Logger::output(std::ostream &os, const std::string &msg, const char *prefix)
00069 {
00070 if (mHasTimestamp)
00071 {
00072 os << getCurrentTime() << ' ';
00073 }
00074
00075 if (prefix)
00076 {
00077 os << prefix << ' ';
00078 }
00079
00080 os << msg << std::endl;
00081 }
00082
00083 void Logger::setLogFile(const std::string &logFile)
00084 {
00085
00086 if (mLogFile.is_open())
00087 {
00088 mLogFile.close();
00089 }
00090
00091
00092 mLogFile.open(logFile.c_str(), std::ios::trunc);
00093
00094 if (!mLogFile.is_open())
00095 {
00096 throw std::ios::failure("unable to open " + logFile + "for writing");
00097 }
00098 else
00099 {
00100
00101
00102 mLogFile.exceptions(std::ios::failbit | std::ios::badbit);
00103 }
00104 }
00105
00106 void Logger::output(const std::string &msg, Level atVerbosity)
00107 {
00108 static const char *prefixes[] =
00109 {
00110 "[FTL]",
00111 "[ERR]",
00112 "[WRN]",
00113 "[INF]",
00114 "[DBG]"
00115 };
00116
00117 if (mVerbosity >= atVerbosity)
00118 {
00119 bool open = mLogFile.is_open();
00120
00121 if (open)
00122 {
00123 output(mLogFile, msg, prefixes[atVerbosity]);
00124 }
00125
00126 if (!open || mTeeMode)
00127 {
00128 output(atVerbosity <= WARN ? std::cerr : std::cout,
00129 msg, prefixes[atVerbosity]);
00130 }
00131 }
00132 }
00133
00134 }