Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/SimpleLog.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#include <string.h>
#include <algorithm>
#include <string>
#include <mutex>

class SimpleLog::Impl
{
Expand Down Expand Up @@ -60,6 +61,7 @@ class SimpleLog::Impl
void rotate(); // this renames older files

friend class SimpleLog;
std::mutex fileMutex;
};

SimpleLog::Impl::Impl()
Expand Down Expand Up @@ -140,6 +142,9 @@ int SimpleLog::Impl::logV(SimpleLog::Impl::Severity s, const char* message, va_l
ix++;
buffer[ix] = 0;

int nBytes = 0; // count bytes output
{
std::lock_guard<std::mutex> lock(fileMutex);
int fd;
if (fp != NULL) {
if ((ix + logFileSize > rotateMaxBytes) && (rotateMaxBytes > 0)) {
Expand All @@ -161,10 +166,11 @@ int SimpleLog::Impl::logV(SimpleLog::Impl::Severity s, const char* message, va_l
fd = fdStdout;
}
}
int nBytes = write(fd, buffer, ix);
nBytes = write(fd, buffer, ix);
if ((fp != NULL) && (nBytes > 0)) {
logFileSize += nBytes;
}
}
if (nBytes != (int)ix) {
return -1;
}
Expand Down
21 changes: 21 additions & 0 deletions test/testSimpleLog.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@

#include <Common/SimpleLog.h>
#include <unistd.h>
#include <thread>
#include <vector>

void logWorker(SimpleLog& log, int threadId, int count) {
for (int i = 0; i < count; ++i) {
log.info("Thread %d - test message %d", threadId, i);
}
}

int main()
{
Expand All @@ -25,5 +33,18 @@ int main()
theLog.info("test message %d", i);
}
// sleep(10);

// test parallel threads
theLog.setLogFile("/tmp/testthread.log", 1000, 10, 0);
const int numThreads = 10;
const int messagesPerThread = 10;
std::vector<std::thread> threads;
for (int t = 0; t < numThreads; ++t) {
threads.emplace_back(logWorker, std::ref(theLog), t, messagesPerThread);
}
for (auto& th : threads) {
th.join();
}

return 0;
}