Log4cpp反复记录日志

时间:2013-07-29 13:40:54

标签: c++ singleton log4cpp

我正在使用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 
thread 1
thread 2

但是test.log是这样的:

[2013-07-29 21:32:34,101] ERROR Test : Create Thread 1 Return
[2013-07-29 21:32:34,101] ERROR Test : Create Thread 2 Return
[2013-07-29 21:32:34,101] ERROR Test : Create Thread 2 Return

我想知道为什么第二次调用日志两次。我使用log4cpp错了吗?

1 个答案:

答案 0 :(得分:4)

这是因为您每次都在Log函数中添加新的appender。每个新的appender都会附加输出。如果你第三次调用它,你就会得到三个输出。

添加appender,设置布局或其他此类一次性配置之类的事情应该只进行一次,最好是在构造函数或初始化函数中。