0

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 リターンの作成

2 回目の通話ログが 2 回記録される理由を知りたいです。log4cpp を間違って使用していますか?

4

1 に答える 1