C++ easylogging 使用教程

GitHub - abumq/easyloggingpp: C++ logging library. It is extremely powerful, extendable, light-weight, fast performing, thread and type safe and consists of many built-in features. It provides ability to write logs in your own customized format. It also provide support for logging your classes, third-party libraries, STL and third-party containers etc.

GitHub - abumq/qmllogging: Lightweight advanced QML Logging (unmaintained) 

#include "easylogging++.h"
#include "easylogging++.cc"
#include <chrono>

INITIALIZE_EASYLOGGINGPP

const char* getIp(const el::LogMessage*) {
	return "192.168.1.1";
}

void myCrashHandler(int sig) {
	LOG(ERROR) << "Woops! Crashed!";
	// FOLLOWING LINE IS ABSOLUTELY NEEDED AT THE END IN ORDER TO ABORT APPLICATION
	//el::Helpers::crashAbort(sig);
}

class Integer : public el::Loggable {
public:
	Integer(int i) : m_underlyingInt(i) {
	}
	Integer& operator=(const Integer& integer) {
		m_underlyingInt = integer.m_underlyingInt;
		return *this;
	}
	// Following line does the trick!
	// Note: el::base::type::ostream_t is either std::wostream or std::ostream depending on unicode enabled or not
	virtual void log(el::base::type::ostream_t& os) const {
		os << m_underlyingInt;
	}
private:
	int m_underlyingInt;
};

class Integer2 {
public:
	Integer2(int i) : m_underlyingInt(i) {
	}
	Integer2& operator=(const Integer2& integer) {
		m_underlyingInt = integer.m_underlyingInt;
		return *this;
	}
	int getInt(void) const { return m_underlyingInt; }
private:
	int m_underlyingInt;
};

// Following line does the trick!
inline MAKE_LOGGABLE(Integer2, integer, os) {
	os << integer.getInt();
	return os;
}

inline MAKE_LOGGABLE(std::chrono::system_clock::time_point, when, os) {
	time_t t = std::chrono::system_clock::to_time_t(when);
	auto tm = std::localtime(&t);
	char buf[1024];
	strftime(buf, sizeof(buf), "%F %T (%Z)", tm);
	os << buf;
	return os;
}

int main_log(int argc, char* argv[]) {
	START_EASYLOGGINGPP(argc, argv);
	LOG(INFO) << "My first info log";

	 Load configuration from file
	//el::Configurations conf("../../../log.conf");
	 Reconfigure single logger
	//el::Loggers::reconfigureLogger("default", conf);
	 Actually reconfigure all loggers instead
	//el::Loggers::reconfigureAllLoggers(conf);
	 Now all the loggers will use configuration from file

	//Using el::Configurations Class
	el::Configurations defaultConf;
	defaultConf.setToDefault();
	// Values are always std::string
	defaultConf.set(el::Level::Info,
		el::ConfigurationType::Format, "%datetime %level %msg");
	// default logger uses default configurations
	el::Loggers::reconfigureLogger("default", defaultConf);
	LOG(INFO) << "Log using default file";
	// To set GLOBAL configurations you may use
	defaultConf.setGlobally(
		el::ConfigurationType::Format, "%date %msg");
	el::Loggers::reconfigureLogger("default", defaultConf);

	el::Configurations c;
	c.setToDefault();
	c.parseFromText("*GLOBAL:\n FORMAT = %level %msg");

	el::Loggers::configureFromGlobal("global.conf");

	el::Helpers::installCustomFormatSpecifier(el::CustomFormatSpecifier("%ip_addr", getIp));
	el::Loggers::reconfigureAllLoggers(el::ConfigurationType::Format, "%datetime %level %ip_addr : %msg");
	LOG(INFO) << "This is request from client";

	el::Logger* l = el::Loggers::getLogger("default");
	bool enabled = l->typedConfigurations()->enabled(el::Level::Info);
	// Or to read log format/pattern
	std::string format =
		l->typedConfigurations()->logFormat(el::Level::Info).format();

	LOG(INFO) << "This is info log";
	CLOG(ERROR, "performance") << "This is info log using performance logger";

	for (int i = 1; i <= 10; ++i) {
		LOG_EVERY_N(2, INFO) << "Logged every second iter";
	}
	// 5 logs written; 2, 4, 6, 7, 10

	for (int i = 1; i <= 10; ++i) {
		LOG_AFTER_N(2, INFO) << "Log after 2 hits; " << i;
	}
	// 8 logs written; 3, 4, 5, 6, 7, 8, 9, 10

	for (int i = 1; i <= 100; ++i) {
		LOG_N_TIMES(3, INFO) << "Log only 3 times; " << i;
	}
	// 3 logs writter; 1, 2, 3

	//info(const char*, const T&, const Args&...)
	//warn(const char*, const T&, const Args&...)
	//error(const char*, const T&, const Args&...)
	//debug(const char*, const T&, const Args&...)
	//fatal(const char*, const T&, const Args&...)
	//trace(const char*, const T&, const Args&...)
	//verbose(int vlevel, const char*, const T&, const Args&...)

	// Use default logger
	el::Logger* defaultLogger = el::Loggers::getLogger("default");

	// STL logging (`ELPP_STL_LOGGING` should be defined)
	std::vector<int> i;
	i.push_back(1);
	defaultLogger->warn("My first ultimate log message %v %v %v", 123, 222, i);

	// Escaping
	defaultLogger->info("My first ultimate log message %% %%v %v %v", 123, 222);
	// %file, %func %line and %loc

	if (VLOG_IS_ON(2)) {
		// Verbosity level 2 is on for this file
	}
	el::Loggers::unregisterLogger("logger-id");
	//el::Loggers::populateAllLoggerIds(std::vector<std::string>&);
	//SHARE_EASYLOGGINGPP(aa)
	//el::Helpers::setStorage(el::base::type::StoragePointer);

	//installPerformanceTrackingCallback<T>(const std::string & id)
	//uninstallPerformanceTrackingCallback<T>(const std::string & id)
	//el::Helpers::installPreRollOutCallback(const PreRollOutCallback & handler)

	//el::Helpers::setCrashHandler(myCrashHandler);
	//LOG(INFO) << "My crash handler!";
	//int* i;
	//*i = 0; // Crash!

	//ELPP_INITIALIZE_SYSLOG("my_proc", LOG_PID | LOG_CONS | LOG_PERROR, LOG_USER) // This is optional, you may not add it if you dont want to specify options
	 Alternatively you may do
	 el::SysLogInitializer elSyslogInit("my_proc", LOG_PID | LOG_CONS | LOG_PERROR, LOG_USER);
	//SYSLOG(INFO) << "This is syslog - read it from /var/log/syslog"

	//el::Logger::flush();
	el::Loggers::flushAll();
}

//void performHeavyTask(int iter) {
//	TIMED_FUNC(timerObj);
//	// Some initializations
//	// Some more heavy tasks
//	usleep(5000);
//	while (iter-- > 0) {
//		TIMED_SCOPE(timerBlkObj, "heavy-iter");
//		// Perform some heavy task in each iter
//		// Notice following sleep varies with each iter
//		usleep(iter * 1000);
//		if (iter % 3) {
//			PERFORMANCE_CHECKPOINT(timerBlkObj);
//		}
//	}
//}
//
//06:33 : 07, 558 INFO Executed[heavy - iter] in[9 ms]
//06 : 33 : 07, 566 INFO Performance checkpoint for block[heavy - iter] : [8 ms]
//06 : 33 : 07, 566 INFO Executed[heavy - iter] in[8 ms]
//06 : 33 : 07, 573 INFO Performance checkpoint for block[heavy - iter] : [7 ms]
//06 : 33 : 07, 573 INFO Executed[heavy - iter] in[7 ms]
//06 : 33 : 07, 579 INFO Executed[heavy - iter] in[6 ms]
//06 : 33 : 07, 584 INFO Performance checkpoint for block[heavy - iter] : [5 ms]
//06 : 33 : 07, 584 INFO Executed[heavy - iter] in[5 ms]
//06 : 33 : 07, 589 INFO Performance checkpoint for block[heavy - iter] : [4 ms]
//06 : 33 : 07, 589 INFO Executed[heavy - iter] in[4 ms]
//06 : 33 : 07, 592 INFO Executed[heavy - iter] in[3 ms]
//06 : 33 : 07, 594 INFO Performance checkpoint for block[heavy - iter] : [2 ms]
//06 : 33 : 07, 594 INFO Executed[heavy - iter] in[2 ms]
//06 : 33 : 07, 595 INFO Performance checkpoint for block[heavy - iter] : [1 ms]
//06 : 33 : 07, 595 INFO Executed[heavy - iter] in[1 ms]
//06 : 33 : 07, 595 INFO Executed[heavy - iter] in[0 ms]
//06 : 33 : 07, 595 INFO Executed[void performHeavyTask(int)] in[51 ms]

//void performHeavyTask(int iter) {
//	// enable performance tracking for verbosity level 4 or higher
//	TIMED_FUNC_IF(timerObj, VLOG_IS_ON(4));
//	// Some more heavy tasks
//}

//ELPP_STL_LOGGING

//
//class NetworkDispatcher : public el::LogDispatchCallback
//{
//public:
//	void updateServer(const std::string& host, int port) {
//		m_client = std::unique_ptr<Client>(new Client(&m_svc, host, std::to_string(port)));
//	}
//protected:
//	void handle(const el::LogDispatchData* data) noexcept override {
//		m_data = data;
//		// Dispatch using default log builder of logger
//		dispatch(m_data->logMessage()->logger()->logBuilder()->build(m_data->logMessage(),
//			m_data->dispatchAction() == el::base::DispatchAction::NormalLog));
//	}
//private:
//	const el::LogDispatchData* m_data;
//	boost::asio::io_service m_svc;
//	std::unique_ptr<Client> m_client;
//
//	void dispatch(el::base::type::string_t&& logLine) noexcept
//	{
//		m_client->send(logLine);
//	}
//};
//
//
//int main() {
//	el::Helpers::installLogDispatchCallback<NetworkDispatcher>("NetworkDispatcher");
//	// you can uninstall default one by
//	// el::Helpers::uninstallLogDispatchCallback<el::base::DefaultLogDispatchCallback>("DefaultLogDispatchCallback");
//	// Set server params
//	NetworkDispatcher* dispatcher = el::Helpers::logDispatchCallback<NetworkDispatcher>("NetworkDispatcher");
//	dispatcher->setEnabled(true);
//	dispatcher->updateServer("127.0.0.1", 9090);
//
//	// Start logging and normal program...
//	LOG(INFO) << "First network log";
//
//	// You can even use a different logger, say "network" and send using a different log pattern
//}


创作不易,小小的支持一下吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码力码力我爱你

创作不易,小小的支持一下吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值