首页 > 代码库 > log4cpp - 使用

log4cpp - 使用

#pragma once
#include "ThreadLock.h"
#include <string>
#include <cstdio>
#include <log4cpp/Category.hh>
#include <log4cpp/Appender.hh>
#include <log4cpp/FileAppender.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/RollingFileAppender.hh>


class QuoteLog
{
public:
static QuoteLog* getInstance();
void loginfo(const std::string& message);
void logdebug(const std::string& message);
void logwarn(const std::string& message);
void logerror(const std::string& message);
private:
QuoteLog();
~QuoteLog();
log4cpp::Category& m_root;
static bool initialized;
static CThreadLock creationLock;

};


---------------------------------------------------------------------------------------------------------------
#include "QuoteLog.h"


#include <iostream>


bool QuoteLog::initialized=false;
CThreadLock QuoteLog::creationLock;




QuoteLog* QuoteLog::getInstance() {
bool needUnlock=false;
if (!initialized) {
creationLock.Lock();
needUnlock=true;
}


static QuoteLog instance;

if (needUnlock) {
initialized=true;
creationLock.UnLock();
}


return &instance;
}


QuoteLog::QuoteLog() : m_root(log4cpp::Category::getRoot().getInstance("QuoteLog"))
{
    log4cpp::PatternLayout* pLayout2 = new log4cpp::PatternLayout();
    pLayout2->setConversionPattern("%d: %p : %m%n");
    log4cpp::RollingFileAppender* rollfileAppender = new log4cpp::RollingFileAppender( "rollfileAppender","quote.log",5*1024,1);
    rollfileAppender->setLayout(pLayout2);
 
    
    m_root.addAppender(rollfileAppender);
    m_root.setPriority(log4cpp::Priority::DEBUG);


}
void QuoteLog::loginfo(const std::string& message)
{
m_root.info(message);
}
void QuoteLog::logdebug(const std::string& message)
{
m_root.debug(message);


}
void QuoteLog::logwarn(const std::string& message)
{
m_root.warn(message);
}
void QuoteLog::logerror(const std::string& message)
{
m_root.error(message);
}


QuoteLog::~QuoteLog()
{
log4cpp::Category::shutdown();
}