的解決方案我已經作出了「解」。它有一些缺陷:它可能重新發明了輪子,它可能不是Poco的習慣用語(我對Poco相當新穎),而且我擔心如果在線程或應用程序關閉期間引發異常,可能會出現死鎖。
但它似乎現在工作。
在頭文件:
struct RC_Semaphore: Poco::Semaphore, Poco::RefCountedObject
{
using Poco::Semaphore::Semaphore;
};
struct SemaphoreLock
{
SemaphoreLock(Poco::Semaphore &sem): sem(sem) { sem.wait(); }
~SemaphoreLock() { sem.set(); }
Poco::Semaphore &sem;
};
struct SynchronizingChannel: Poco::Channel, noncopyable
{
SynchronizingChannel(Poco::AutoPtr<RC_Semaphore> sem, Poco::AutoPtr<Poco::Channel> dest)
: sem(sem), dest(dest) {}
virtual void log(const Poco::Message& msg)
{
SemaphoreLock lock(*sem);
dest->log(msg);
}
private:
Poco::AutoPtr<RC_Semaphore> sem;
Poco::AutoPtr<Poco::Channel> dest;
} ;
用法:
// Synchronization for log channels outputting to console
auto semConsole = make_AutoPtr<RC_Semaphore>(1);
// Logging channel - main
auto chanMainRaw = make_AutoPtr<Poco::WindowsColorConsoleChannel>();
chanMainRaw->setProperty("debugColor", "green");
auto chanMain = make_AutoPtr<SynchronizingChannel>(semConsole, chanMainRaw);
// Channel that will be used by thread
auto chanThreadRaw = make_AutoPtr<Poco::WindowsColorConsoleChannel>();
chanThreadRaw->setProperty("debugColor", "magenta");
auto chanThread = make_AutoPtr<SynchronizingChannel>(semConsole, chanThreadRaw);
// (other code to set up filters can go here)
logger().setChannel(chanMain);
OtherThread::logger().setChannel(chanThread);
NB。 make_AutoPtr
與std::make_unique
相同,但與Poco::AutoPtr
相反,我使用它來避免必須複製類型名稱。
當然,在關鍵部分中可以將每次調用都打包到記錄器中,但我希望有更好的東西,內置到日誌框架中的一些東西能夠處理這個問題。 –
你是如何創建這些不同的記錄器對象? – Alex
@Alex線程使用'Poco :: Logger :: get(「bla」)',主應用程序使用'Poco :: Application'的'logger()'成員函數,在每種情況下,我都通過附加WindowsColorConsoleChannel使用'setChannel' –