0
나는 싱글 톤 모드로 설계된 Log 클래스를 생성하기 위해 log4cpp를 사용하고 있습니다. 여기 내 Log.hLog4cpp 레코드 로그 반복
#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 : g++ -g Main.cpp Log.cpp -lpthread -llog4cpp
와
#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;
}
컴파일 및 실행 . 출력은 다음과 같습니다
# ./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를 잘못 사용하고 있습니까?
로그 기능이 매번 새로운 것을 생성하는 이유는 무엇입니까? (절대로 삭제되지 않겠습니까?) – doctorlove
올바르게 기억한다면 appender, layout, priority를 한번 설정하면됩니다. –
appender 레이아웃과 우선 순위를 한 번 설정하는 방법은 무엇입니까? 'getInstance()'함수에서 그것을합니까? –