我正在使用 log4cpp 创建一个 Log 类,该类是在单例模式下设计的。这是我的 Log.h
#include <cstdio>
#include <cstring>
#include <cstdarg>
#include <log4cpp/Category.hh>
#include <log4cpp/Appender.hh>
#include <log4cpp/FileAppender.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/PatternLayout.hh>
class CtagentLog
{
public:
static CtagentLog& getInstance() {
static CtagentLog instance;
return instance;
}
void Log(int type, char *content);
private:
CtagentLog();
CtagentLog(CtagentLog const&);
CtagentLog& operator=(CtagentLog const &);
~CtagentLog();
// char *log_file;
// log4cpp::PatternLayout *plt;
// log4cpp::Appender *app;
void itoa(int n, char* str, int radix);
};
这是我的 Log.cpp 文件:
#include "Log.h"
CtagentLog::CtagentLog()
{
}
CtagentLog::~CtagentLog()
{
}
/*
* type=1 ERROR
* type=2 WARN
* type=3 INFO
*/
void CtagentLog::Log(int type, char *content)
{
log4cpp::PatternLayout *plt = new log4cpp::PatternLayout();
plt->setConversionPattern("[%d] %p %c %x: %m%n");
log4cpp::Appender *app = new log4cpp::FileAppender("fileAppender", "test.log");
app->setLayout(plt);
log4cpp::Category &root = log4cpp::Category::getRoot().getInstance("Test");
root.addAppender(app);
root.setPriority(log4cpp::Priority::DEBUG);
switch(type){
case 1: root.error(content); break;
case 2: root.warn(content); break;
case 3: root.info(content); break;
default: root.info(content); break;
}
}
最后是我的 testmain.cpp:
#include "Log.h"
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void *func1(void *arg)
{
printf("thread 1\n");
}
void *func2(void *arg)
{
printf("thread 2\n");
}
int main(void)
{
pthread_t tid1;
pthread_t tid2;
pthread_create(&tid1, NULL, func1, NULL);
pthread_join(tid1, NULL);
CtagentLog::getInstance().Log(1,"Create Thread 1 Return");
pthread_create(&tid2, NULL, func2, NULL);
pthread_join(tid2, NULL);
CtagentLog::getInstance().Log(1,"Create Thread 2 Return");
return 0;
}
编译g++ -g Main.cpp Log.cpp -lpthread -llog4cpp
并运行它。输出是:
# ./a.out 线程 1 线程 2
但 test.log 是这样的:
[2013-07-29 21:32:34,101] 错误测试:创建线程 1 返回 [2013-07-29 21:32:34,101] 错误测试:创建线程 2 返回 [2013-07-29 21:32:34,101] 错误测试:创建线程 2 返回
我想知道为什么第二次通话记录两次。我使用 log4cpp 错了吗?