我可以找到 log4j 的解决方案,但不能找到 log4cxx。
问问题
1340 次
2 回答
2
我有一个简单的解决方案。
extern LoggerPtr logger;
#define LOG_TRACE(msg) LOG4CXX_TRACE(logger, msg)
#define LOG_DEBUG(msg) LOG4CXX_DEBUG(logger, msg)
#define LOG_INFO(msg) LOG4CXX_INFO(logger, msg)
#define LOG_INFO_H(msg) LOG4CXX_INFO(logger, "\33[0;42m" << msg << "\33[0m") // green
#define LOG_WARN(msg) LOG4CXX_WARN(logger, "\33[0;43m" << msg << "\33[0m") // yellow
#define LOG_ERROR(msg) LOG4CXX_ERROR(logger, "\33[0;41m" << msg << "\33[0m") // red
#define LOG_FATAL(msg) LOG4CXX_FATAL(logger, "\33[0;41m" << msg << "\33[0m") // red
于 2013-07-30T06:19:23.347 回答
1
当谷歌把我带到这里时,我发布了我的解决方案,希望它能帮助别人。
我为 c++ 实现了我为 log4j 找到的这个Layout
解决方案,创建了一个继承自PatternLayout
. 它只是将标准的输出包装log4cxx::PatternLayout
在颜色转义序列中。
我将以下内容放入 cpp 文件中(如果您愿意,可以将其拆分为 hpp/cpp):
#include <log4cxx/helpers/pool.h>
#include <log4cxx/patternlayout.h>
namespace log4cxx{
class LOG4CXX_EXPORT ColorPatternLayout : public log4cxx::PatternLayout
{
public:
DECLARE_LOG4CXX_OBJECT(ColorPatternLayout)
BEGIN_LOG4CXX_CAST_MAP()
LOG4CXX_CAST_ENTRY(ColorPatternLayout)
LOG4CXX_CAST_ENTRY_CHAIN(Layout)
END_LOG4CXX_CAST_MAP()
ColorPatternLayout();
ColorPatternLayout(const log4cxx::LogString &s);
virtual void format(log4cxx::LogString &output, const log4cxx::spi::LoggingEventPtr &event, log4cxx::helpers::Pool &pool) const override;
};
LOG4CXX_PTR_DEF(ColorPatternLayout);
}
using namespace log4cxx;
IMPLEMENT_LOG4CXX_OBJECT(ColorPatternLayout);
ColorPatternLayout::ColorPatternLayout() : log4cxx::PatternLayout(){}
ColorPatternLayout::ColorPatternLayout(const LogString &s): log4cxx::PatternLayout(s){}
void ColorPatternLayout::format(LogString &output, const spi::LoggingEventPtr &event, helpers::Pool &pool) const
{
log4cxx::LogString tmp;
log4cxx::PatternLayout::format(tmp,event,pool);
log4cxx::LevelPtr lvl = event->getLevel();
switch (lvl->toInt()){
case log4cxx::Level::FATAL_INT:
output.append("\u001b[0;41m"); //red BG
break;
case log4cxx::Level::ERROR_INT:
output.append("\u001b[0;31m"); // red FG
break;
case log4cxx::Level::WARN_INT:
output.append("\u001b[0;33m"); //Yellow FG
break;
case log4cxx::Level::INFO_INT:
output.append("\u001b[1m"); // Bright
break;
case log4cxx::Level::DEBUG_INT:
output.append("\u001b[2;32m"); // Green FG
break;
case log4cxx::Level::TRACE_INT:
output.append("\u001b[0;30m"); // Black FG
break;
default:
break;
}
output.append(tmp);
output.append("\u001b[m");
}
当然,配置您的记录器以使用此布局类,并像使用 PatterLayout 一样使用它,例如在log4cxx.properties
文件中:
log4j.appender.EXAMPLE=org.apache.log4j.ConsoleAppender
log4j.appender.EXAMPLE.layout=org.apache.log4j.ColorPatternLayout
log4j.appender.EXAMPLE.layout.ConversionPattern=%-5p %c %x - %m%n
于 2018-06-06T16:44:58.743 回答