You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@logging.apache.org by sw...@apache.org on 2024/12/19 06:05:49 UTC
(logging-log4cxx) 01/01: Periodically flush buffered file output
This is an automated email from the ASF dual-hosted git repository.
swebb2066 pushed a commit to branch add_asynch_buffer_flush_option
in repository https://gitbox.apache.org/repos/asf/logging-log4cxx.git
commit bed196f2912e18ec0b4731faf2ae0115474ace15
Author: Stephen Webb <sw...@gmail.com>
AuthorDate: Thu Dec 19 17:05:29 2024 +1100
Periodically flush buffered file output
---
src/main/cpp/fileappender.cpp | 22 +++
src/main/cpp/filewatchdog.cpp | 103 +++++--------
src/main/cpp/threadutility.cpp | 165 ++++++++++++++++++++-
src/main/include/log4cxx/fileappender.h | 1 +
src/main/include/log4cxx/helpers/filewatchdog.h | 3 -
src/main/include/log4cxx/helpers/threadutility.h | 18 +++
.../include/log4cxx/private/fileappender_priv.h | 6 +
.../include/log4cxx/private/writerappender_priv.h | 6 +-
8 files changed, 242 insertions(+), 82 deletions(-)
diff --git a/src/main/cpp/fileappender.cpp b/src/main/cpp/fileappender.cpp
index da536074..321a67de 100644
--- a/src/main/cpp/fileappender.cpp
+++ b/src/main/cpp/fileappender.cpp
@@ -25,6 +25,7 @@
#include <log4cxx/helpers/outputstreamwriter.h>
#include <log4cxx/helpers/bufferedwriter.h>
#include <log4cxx/helpers/bytebuffer.h>
+#include "log4cxx/helpers/threadutility.h"
#include <log4cxx/private/writerappender_priv.h>
#include <log4cxx/private/fileappender_priv.h>
#include <mutex>
@@ -81,6 +82,8 @@ FileAppender::FileAppender(std::unique_ptr<FileAppenderPriv> priv)
FileAppender::~FileAppender()
{
finalize();
+ if (_priv->bufferedIO && 0 < _priv->bufferedSeconds)
+ ThreadUtility::instance()->removePeriodicTask(getName());
}
void FileAppender::setAppend(bool fileAppend1)
@@ -140,6 +143,11 @@ void FileAppender::setOption(const LogString& option,
std::lock_guard<std::recursive_mutex> lock(_priv->mutex);
_priv->bufferSize = OptionConverter::toFileSize(value, 8 * 1024);
}
+ else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFEREDSECONDS"), LOG4CXX_STR("bufferedseconds")))
+ {
+ std::lock_guard<std::recursive_mutex> lock(_priv->mutex);
+ _priv->bufferedSeconds = OptionConverter::toInt(value, 0);
+ }
else
{
WriterAppender::setOption(option, value);
@@ -184,6 +192,20 @@ void FileAppender::activateOptionsInternal(Pool& p)
if (errors == 0)
{
WriterAppender::activateOptions(p);
+
+ if (!_priv->bufferedIO)
+ ;
+ else if (0 < _priv->bufferedSeconds)
+ {
+ ThreadUtility::instance()->addPeriodicTask(getName()
+ , std::bind(&WriterAppenderPriv::flush, _priv)
+ , std::chrono::seconds(_priv->bufferedSeconds)
+ );
+ }
+ else if (0 == _priv->bufferedSeconds)
+ {
+ ThreadUtility::instance()->removePeriodicTask(getName());
+ }
}
}
diff --git a/src/main/cpp/filewatchdog.cpp b/src/main/cpp/filewatchdog.cpp
index 903d9308..7aaf0c94 100644
--- a/src/main/cpp/filewatchdog.cpp
+++ b/src/main/cpp/filewatchdog.cpp
@@ -25,10 +25,6 @@
#include <functional>
#include <chrono>
-#if LOG4CXX_EVENTS_AT_EXIT
-#include <log4cxx/private/atexitregistry.h>
-#endif
-
using namespace LOG4CXX_NS;
using namespace LOG4CXX_NS::helpers;
@@ -37,14 +33,9 @@ long FileWatchdog::DEFAULT_DELAY = 60000;
struct FileWatchdog::FileWatchdogPrivate{
FileWatchdogPrivate(const File& file1) :
file(file1), delay(DEFAULT_DELAY), lastModif(0),
- warnedAlready(false), interrupted(0), thread()
-#if LOG4CXX_EVENTS_AT_EXIT
- , atExitRegistryRaii([this]{stopWatcher();})
-#endif
+ warnedAlready(false)
{ }
- ~FileWatchdogPrivate()
- { stopWatcher(); }
/**
The name of the file to observe for changes.
@@ -57,26 +48,14 @@ struct FileWatchdog::FileWatchdogPrivate{
long delay;
log4cxx_time_t lastModif;
bool warnedAlready;
- volatile int interrupted;
+#if LOG4CXX_ABI_VERSION <= 15
+ int interrupted{ 0 };
Pool pool;
std::thread thread;
std::condition_variable interrupt;
std::mutex interrupt_mutex;
-
-#if LOG4CXX_EVENTS_AT_EXIT
- helpers::AtExitRegistry::Raii atExitRegistryRaii;
#endif
-
- void stopWatcher()
- {
- {
- std::lock_guard<std::mutex> lock(interrupt_mutex);
- interrupted = 0xFFFF;
- }
- interrupt.notify_all();
- if (thread.joinable())
- thread.join();
- }
+ LogString taskName{LOG4CXX_STR("FileWatchdog")};
};
FileWatchdog::FileWatchdog(const File& file1)
@@ -86,20 +65,22 @@ FileWatchdog::FileWatchdog(const File& file1)
FileWatchdog::~FileWatchdog()
{
- if (m_priv->thread.joinable())
- stop();
+ stop();
}
bool FileWatchdog::is_active()
{
- return m_priv->thread.joinable();
+ return ThreadUtility::instance()->hasPeriodicTask(m_priv->taskName);
}
void FileWatchdog::stop()
{
- LogLog::debug(LOG4CXX_STR("Stopping file watchdog"));
- m_priv->stopWatcher();
+ if (is_active())
+ {
+ LogLog::debug(LOG4CXX_STR("Stopping file watchdog"));
+ ThreadUtility::instance()->removePeriodicTask(m_priv->taskName);
+ }
}
const File& FileWatchdog::file()
@@ -141,50 +122,38 @@ void FileWatchdog::checkAndConfigure()
}
}
-void FileWatchdog::run()
-{
- if (LogLog::isDebugEnabled())
- {
- LogString msg(LOG4CXX_STR("Checking ["));
- msg += m_priv->file.getPath();
- msg += LOG4CXX_STR("] at ");
- StringHelper::toString((int)m_priv->delay, m_priv->pool, msg);
- msg += LOG4CXX_STR(" ms interval");
- LogLog::debug(msg);
- }
-
- while (!is_interrupted())
- {
- std::unique_lock<std::mutex> lock( m_priv->interrupt_mutex );
- if (!m_priv->interrupt.wait_for( lock, std::chrono::milliseconds( m_priv->delay ),
- std::bind(&FileWatchdog::is_interrupted, this) ))
- checkAndConfigure();
- }
-
- if (LogLog::isDebugEnabled())
- {
- LogString msg2(LOG4CXX_STR("Stop checking ["));
- msg2 += m_priv->file.getPath();
- msg2 += LOG4CXX_STR("]");
- LogLog::debug(msg2);
- }
-}
-
void FileWatchdog::start()
{
checkAndConfigure();
- if (!m_priv->thread.joinable())
+ auto p = ThreadUtility::instance();
+ if (!p->hasPeriodicTask(m_priv->taskName))
{
- m_priv->interrupted = 0;
- m_priv->thread = ThreadUtility::instance()->createThread(LOG4CXX_STR("FileWatchdog"), &FileWatchdog::run, this);
+ if (LogLog::isDebugEnabled())
+ {
+ Pool p;
+ LogString msg(LOG4CXX_STR("Checking ["));
+ msg += m_priv->file.getPath();
+ msg += LOG4CXX_STR("] at ");
+ StringHelper::toString((int)m_priv->delay, p, msg);
+ msg += LOG4CXX_STR(" ms interval");
+ LogLog::debug(msg);
+ }
+ p->addPeriodicTask(m_priv->taskName
+ , std::bind(&FileWatchdog::checkAndConfigure, this)
+ , std::chrono::milliseconds(m_priv->delay)
+ );
}
}
-bool FileWatchdog::is_interrupted()
-{
- return m_priv->interrupted == 0xFFFF;
-}
-
void FileWatchdog::setDelay(long delay1){
m_priv->delay = delay1;
+ auto p = ThreadUtility::instance();
+ if (p->hasPeriodicTask(m_priv->taskName))
+ {
+ p->removePeriodicTask(m_priv->taskName);
+ p->addPeriodicTask(m_priv->taskName
+ , std::bind(&FileWatchdog::checkAndConfigure, this)
+ , std::chrono::milliseconds(m_priv->delay)
+ );
+ }
}
diff --git a/src/main/cpp/threadutility.cpp b/src/main/cpp/threadutility.cpp
index d4211ce5..6077d73d 100644
--- a/src/main/cpp/threadutility.cpp
+++ b/src/main/cpp/threadutility.cpp
@@ -31,6 +31,10 @@
#include <processthreadsapi.h>
#endif
+#if LOG4CXX_EVENTS_AT_EXIT
+#include <log4cxx/private/atexitregistry.h>
+#endif
+
namespace LOG4CXX_NS
{
namespace helpers
@@ -39,15 +43,57 @@ namespace helpers
struct ThreadUtility::priv_data
{
priv_data()
+#if LOG4CXX_EVENTS_AT_EXIT
+ : atExitRegistryRaii{ []{ stopThread(); } }
+#endif
{
- start_pre = nullptr;
- started = nullptr;
- start_post = nullptr;
}
- ThreadStartPre start_pre;
- ThreadStarted started;
- ThreadStartPost start_post;
+ ~priv_data()
+ { stopThread(); }
+
+ ThreadStartPre start_pre{nullptr};
+ ThreadStarted started{nullptr};
+ ThreadStartPost start_post{nullptr};
+
+ using TimePoint = std::chrono::time_point<std::chrono::system_clock>;
+ struct NamedPeriodicFunction
+ {
+ LogString name;
+ Period delay;
+ TimePoint nextRun;
+ int errorCount;
+ std::function<void()> f;
+ };
+ using JobStore = std::list<NamedPeriodicFunction>;
+ JobStore jobs;
+ std::mutex job_mutex;
+ std::thread thread;
+ std::condition_variable interrupt;
+ std::mutex interrupt_mutex;
+ bool terminated{false};
+ int retryCount{2};
+ Period maxDelay;
+
+ void doPeriodicTasks();
+
+ void setTerminated()
+ {
+ std::lock_guard<std::mutex> lock(interrupt_mutex);
+ terminated = true;
+ }
+
+ void stopThread()
+ {
+ setTerminated();
+ interrupt.notify_all();
+ if (thread.joinable())
+ thread.join();
+ }
+
+#if LOG4CXX_EVENTS_AT_EXIT
+ helpers::AtExitRegistry::Raii atExitRegistryRaii;
+#endif
};
#if LOG4CXX_HAS_PTHREAD_SIGMASK
@@ -55,8 +101,8 @@ struct ThreadUtility::priv_data
static thread_local bool sigmask_valid;
#endif
-ThreadUtility::ThreadUtility() :
- m_priv( new priv_data() )
+ThreadUtility::ThreadUtility()
+ : m_priv( std::make_unique<priv_data>() )
{
// Block signals by default.
configureFuncs( std::bind( &ThreadUtility::preThreadBlockSignals, this ),
@@ -198,5 +244,108 @@ ThreadStartPost ThreadUtility::postStartFunction()
return m_priv->start_post;
}
+/**
+ * Add a periodic task
+ */
+void ThreadUtility::addPeriodicTask(const LogString& name, std::function<void()> f, const Period& delay)
+{
+ std::lock_guard<std::mutex> lock(m_priv->job_mutex);
+ if (m_priv->maxDelay < delay)
+ m_priv->maxDelay = delay;
+ priv_data::TimePoint currentTime = std::chrono::system_clock::now();
+ m_priv->jobs.emplace_back(name, delay, currentTime + delay, 0, f);
+ if (!m_priv->thread.joinable())
+ m_priv->thread = createThread(LOG4CXX_STR("log4cxx"), std::bind(&priv_data::doPeriodicTasks, m_priv.get()));
+ else
+ m_priv->interrupt.notify_one();
+}
+
+/**
+ * Is this already running a \c taskName periodic task?
+ */
+bool ThreadUtility::hasPeriodicTask(const LogString& name)
+{
+ std::lock_guard<std::mutex> lock(m_priv->job_mutex);
+ auto pItem = std::find_if(m_priv->jobs.begin(), m_priv->jobs.end()
+ , [&name](const priv_data::NamedPeriodicFunction& item)
+ { return name == item.name; }
+ );
+ return m_priv->jobs.end() != pItem;
+}
+
+/**
+ * Remove the \c taskName periodic task
+ */
+void ThreadUtility::removePeriodicTask(const LogString& name)
+{
+ std::lock_guard<std::mutex> lock(m_priv->job_mutex);
+ auto pItem = std::find_if(m_priv->jobs.begin(), m_priv->jobs.end()
+ , [&name](const priv_data::NamedPeriodicFunction& item)
+ { return name == item.name; }
+ );
+ if (m_priv->jobs.end() != pItem)
+ m_priv->jobs.erase(pItem);
+}
+
+// Run ready tasks
+void ThreadUtility::priv_data::doPeriodicTasks()
+{
+ while (!this->terminated)
+ {
+ if (this->jobs.empty())
+ break;
+ auto currentTime = std::chrono::system_clock::now();
+ TimePoint nextOperationTime = currentTime + this->maxDelay;
+ {
+ std::lock_guard<std::mutex> lock(this->job_mutex);
+ for (auto& item : this->jobs)
+ {
+ if (this->terminated)
+ break;
+ if (item.nextRun <= currentTime)
+ {
+ if (LogLog::isDebugEnabled())
+ LogLog::debug(LOG4CXX_STR("running ") + item.name);
+ try
+ {
+ item.f();
+ item.nextRun = std::chrono::system_clock::now() + item.delay;
+ if (item.nextRun < nextOperationTime)
+ nextOperationTime = item.nextRun;
+ item.errorCount = 0;
+ }
+ catch (std::exception& ex)
+ {
+ LogLog::warn(item.name, ex);
+ ++item.errorCount;
+ }
+ catch (...)
+ {
+ LogLog::warn(item.name + LOG4CXX_STR(" threw an exception"));
+ ++item.errorCount;
+ }
+ }
+ else if (item.nextRun < nextOperationTime)
+ nextOperationTime = item.nextRun;
+ }
+ }
+ // Remove faulty tasks
+ while (1)
+ {
+ std::lock_guard<std::mutex> lock(this->job_mutex);
+ auto pItem = std::find_if(this->jobs.begin(), this->jobs.end()
+ , [this](const NamedPeriodicFunction& item)
+ { return this->retryCount < item.errorCount; }
+ );
+ if (this->jobs.end() == pItem)
+ break;
+ this->jobs.erase(pItem);
+ }
+
+ std::unique_lock<std::mutex> lock(this->interrupt_mutex);
+ this->interrupt.wait_until(lock, nextOperationTime);
+ }
+}
+
} //namespace helpers
} //namespace log4cxx
diff --git a/src/main/include/log4cxx/fileappender.h b/src/main/include/log4cxx/fileappender.h
index ebfd2dba..ed4d604e 100644
--- a/src/main/include/log4cxx/fileappender.h
+++ b/src/main/include/log4cxx/fileappender.h
@@ -130,6 +130,7 @@ class LOG4CXX_EXPORT FileAppender : public WriterAppender
FileName | {any} | -
Append | True,False | True
BufferedIO | True,False | False
+ BufferedSeconds | {any} | 5
ImmediateFlush | True,False | False
BufferSize | (\ref fileSz1 "1") | 8 KB
diff --git a/src/main/include/log4cxx/helpers/filewatchdog.h b/src/main/include/log4cxx/helpers/filewatchdog.h
index cbfc7b69..a3f5a1dd 100644
--- a/src/main/include/log4cxx/helpers/filewatchdog.h
+++ b/src/main/include/log4cxx/helpers/filewatchdog.h
@@ -72,9 +72,6 @@ class LOG4CXX_EXPORT FileWatchdog
bool is_active();
private:
- void run();
- bool is_interrupted();
-
FileWatchdog(const FileWatchdog&);
FileWatchdog& operator=(const FileWatchdog&);
diff --git a/src/main/include/log4cxx/helpers/threadutility.h b/src/main/include/log4cxx/helpers/threadutility.h
index 9d0127c5..353bc301 100644
--- a/src/main/include/log4cxx/helpers/threadutility.h
+++ b/src/main/include/log4cxx/helpers/threadutility.h
@@ -21,6 +21,7 @@
#include <thread>
#include <functional>
#include <memory>
+#include <chrono>
#include "log4cxx/logstring.h"
#include "widelife.h"
@@ -153,6 +154,23 @@ class LOG4CXX_EXPORT ThreadUtility
return t;
}
+
+ using Period = std::chrono::milliseconds;
+
+ /**
+ * Add a periodic task
+ */
+ void addPeriodicTask(const LogString& name, std::function<void()> f, const Period& delay);
+
+ /**
+ * Has a \c taskName periodic task already been added?
+ */
+ bool hasPeriodicTask(const LogString& name);
+
+ /**
+ * Remove the \c taskName periodic task
+ */
+ void removePeriodicTask(const LogString& name);
};
} /* namespace helpers */
diff --git a/src/main/include/log4cxx/private/fileappender_priv.h b/src/main/include/log4cxx/private/fileappender_priv.h
index 11af7fbc..eaa190cb 100644
--- a/src/main/include/log4cxx/private/fileappender_priv.h
+++ b/src/main/include/log4cxx/private/fileappender_priv.h
@@ -60,6 +60,12 @@ struct FileAppender::FileAppenderPriv : public WriterAppender::WriterAppenderPri
/**
How big should the IO buffer be? Default is 8K. */
int bufferSize;
+
+ /**
+ The number of seconds between each asynchronous output buffer flush.
+ Only active when <code>bufferedIO == true</code>.
+ */
+ int bufferedSeconds{ 5 };
};
}
diff --git a/src/main/include/log4cxx/private/writerappender_priv.h b/src/main/include/log4cxx/private/writerappender_priv.h
index 30f52eea..02e3a798 100644
--- a/src/main/include/log4cxx/private/writerappender_priv.h
+++ b/src/main/include/log4cxx/private/writerappender_priv.h
@@ -37,7 +37,7 @@ struct WriterAppender::WriterAppenderPriv : public AppenderSkeleton::AppenderSke
AppenderSkeletonPrivate(),
immediateFlush(true)
#if LOG4CXX_EVENTS_AT_EXIT
- , atExitRegistryRaii([this]{atExitActivated();})
+ , atExitRegistryRaii{ [this]{ flush(); } }
#endif
{
}
@@ -62,14 +62,12 @@ struct WriterAppender::WriterAppenderPriv : public AppenderSkeleton::AppenderSke
{
}
-#if LOG4CXX_EVENTS_AT_EXIT
- void atExitActivated()
+ void flush()
{
std::lock_guard<std::recursive_mutex> lock(mutex);
if (writer)
writer->flush(pool);
}
-#endif
/**
Immediate flush means that the underlying writer or output stream