diff options
author | Andrei Karas <akaras@inbox.ru> | 2014-01-14 00:56:03 +0300 |
---|---|---|
committer | Andrei Karas <akaras@inbox.ru> | 2014-01-14 00:56:20 +0300 |
commit | 8e4f4e04ca61594e3dec31bad70eaf6cdf86ad8f (patch) | |
tree | b246d23998da0af196460f42af22b7c89b845b2c /src/logger.cpp | |
parent | c28aa31fe3d701530280ac92c92e8dff36e65f03 (diff) | |
download | manaverse-8e4f4e04ca61594e3dec31bad70eaf6cdf86ad8f.tar.gz manaverse-8e4f4e04ca61594e3dec31bad70eaf6cdf86ad8f.tar.bz2 manaverse-8e4f4e04ca61594e3dec31bad70eaf6cdf86ad8f.tar.xz manaverse-8e4f4e04ca61594e3dec31bad70eaf6cdf86ad8f.zip |
add support for thread safe writing to log.
Diffstat (limited to 'src/logger.cpp')
-rw-r--r-- | src/logger.cpp | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/src/logger.cpp b/src/logger.cpp index bac895954..a4cc5096b 100644 --- a/src/logger.cpp +++ b/src/logger.cpp @@ -64,6 +64,9 @@ Logger *logger = nullptr; // Log object Logger::Logger() : mLogFile(), + mDelayedLog(), + mMutex(SDL_CreateMutex()), + mThreadLocked(false), mLogToStandardOut(true), mDebugLog(false) { @@ -73,6 +76,7 @@ Logger::~Logger() { if (mLogFile.is_open()) mLogFile.close(); + SDL_DestroyMutex(mMutex); } void Logger::setLogFile(const std::string &logFilename) @@ -169,6 +173,60 @@ void Logger::log(const char *const log_text, ...) delete [] buf; } +void Logger::log_r(const char *const log_text, ...) +{ + SDL_mutexP(mMutex); + + unsigned size = 1024; + if (strlen(log_text) * 3 > size) + size = static_cast<unsigned>(strlen(log_text) * 3); + + char* buf = new char[size + 1]; + va_list ap; + + // Use a temporary buffer to fill in the variables + va_start(ap, log_text); + vsnprintf(buf, size, log_text, ap); + buf[size] = 0; + va_end(ap); + + // Get the current system time + timeval tv; + gettimeofday(&tv, nullptr); + + // Print the log entry + std::stringstream timeStr; + DATESTREAM + LOG_ANDROID(buf) + + if (mLogFile.is_open()) + { + timeStr << buf << std::endl; + mThreadLocked = true; + mDelayedLog.push_back(timeStr.str()); + mThreadLocked = false; + } + + if (mLogToStandardOut) + std::cout << timeStr.str() << buf << std::endl; + + // Delete temporary buffer + delete [] buf; + + SDL_mutexV(mMutex); +} + +void Logger::flush() +{ + if (!mThreadLocked) + { + SDL_mutexP(mMutex); + FOR_EACH (std::vector<std::string>::const_iterator, it, mDelayedLog) + mLogFile << *it; + SDL_mutexV(mMutex); + } +} + // here string must be safe for any usage void Logger::safeError(const std::string &error_text) { |