00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #include <iostream>
00023 #include <sstream>
00024
00025 #include <sys/time.h>
00026
00027 #ifdef WIN32
00028 #include <windows.h>
00029 #elif __APPLE__
00030 #include <Carbon/Carbon.h>
00031 #endif
00032
00033 #include "log.h"
00034
00035 #include "gui/widgets/chattab.h"
00036
00037 Logger::Logger():
00038 mLogToStandardOut(false),
00039 mChatWindow(NULL)
00040 {
00041 }
00042
00043 Logger::~Logger()
00044 {
00045 if (mLogFile.is_open())
00046 {
00047 mLogFile.close();
00048 }
00049 }
00050
00051 void Logger::setLogFile(const std::string &logFilename)
00052 {
00053 mLogFile.open(logFilename.c_str(), std::ios_base::trunc);
00054
00055 if (!mLogFile.is_open())
00056 {
00057 std::cout << "Warning: error while opening " << logFilename <<
00058 " for writing.\n";
00059 }
00060 }
00061
00062 void Logger::log(const char *log_text, ...)
00063 {
00064 if (!mLogFile.is_open())
00065 {
00066 return;
00067 }
00068
00069 char* buf = new char[1024];
00070 va_list ap;
00071
00072
00073 va_start(ap, log_text);
00074 vsprintf(buf, log_text, ap);
00075 va_end(ap);
00076
00077
00078 timeval tv;
00079 gettimeofday(&tv, NULL);
00080
00081
00082 std::stringstream timeStr;
00083 timeStr << "["
00084 << ((((tv.tv_sec / 60) / 60) % 24 < 10) ? "0" : "")
00085 << (int)(((tv.tv_sec / 60) / 60) % 24)
00086 << ":"
00087 << (((tv.tv_sec / 60) % 60 < 10) ? "0" : "")
00088 << (int)((tv.tv_sec / 60) % 60)
00089 << ":"
00090 << ((tv.tv_sec % 60 < 10) ? "0" : "")
00091 << (int)(tv.tv_sec % 60)
00092 << "."
00093 << (((tv.tv_usec / 10000) % 100) < 10 ? "0" : "")
00094 << (int)((tv.tv_usec / 10000) % 100)
00095 << "] ";
00096
00097 mLogFile << timeStr.str() << buf << std::endl;
00098
00099 if (mLogToStandardOut)
00100 {
00101 std::cout << timeStr.str() << buf << std::endl;
00102 }
00103
00104 if (mChatWindow)
00105 {
00106 localChatTab->chatLog(buf, BY_LOGGER);
00107 }
00108
00109
00110 delete[] buf;
00111 }
00112
00113 void Logger::error(const std::string &error_text)
00114 {
00115 log("Error: %s", error_text.c_str());
00116 #ifdef WIN32
00117 MessageBox(NULL, error_text.c_str(), "Error", MB_ICONERROR | MB_OK);
00118 #elif defined __APPLE__
00119 Str255 msg;
00120 CFStringRef error;
00121 error = CFStringCreateWithCString(NULL,
00122 error_text.c_str(),
00123 kCFStringEncodingMacRoman);
00124 CFStringGetPascalString(error, msg, 255, kCFStringEncodingMacRoman);
00125 StandardAlert(kAlertStopAlert,
00126 "\pError",
00127 (ConstStr255Param) msg, NULL, NULL);
00128 #else
00129 std::cerr << "Error: " << error_text << std::endl;
00130 #endif
00131 exit(1);
00132 }