c++ - Log4cpp 重复记录日志

标签 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?

最佳答案

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

诸如添加附加程序、设置布局或其他此类一次性配置之类的事情应该只完成一次,最好在构造函数或初始化函数中完成。

关于c++ - Log4cpp 重复记录日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17925643/

相关文章:

c++ - Tesseract总是在图片中缺少文本行

c++ - 开发 C++ 错误 : expected declaration before '}' token

ios - 拥有同步线程的目的

c++ - 使用 C++ 记录本地化的最佳方法

c++ - log4cpp: Linux 找不到 lib 文件

c++ - 基于 log4j 的记录器 : log4cpp vs log4cplus vs log4cxx

c++ - OpenGL 错误 1282 与 glEndList()

c++ - 模板化函数只接受右值

iphone - 单例类中的 NSMutableArray 总是返回计数 0/从不保留其对象

.net - .NET 中的单例约定