做服务器开发首要做的事情,就是将日志系统建立起来。这个系统也是方便我们检查服务器的问题。
初始化日志系统
这是一个初始化日志系统的代码。我这里是使用了一个配置文件来做boost.log的设置的。所以代码写起来是非常的简洁。
#include
#include
#include
#include
#include
#include
#include
bool init_log_environment(std::string _cfg)
{
namespace logging = boost::log;
using namespace logging::trivial;
if (!boost::filesystem::exists("./log/"))
{
boost::filesystem::create_directory("./log/");
}
logging::add_common_attributes();
logging::register_simple_formatter_factory("Severity");
logging::register_simple_filter_factory("Severity");
std::ifstream file(_cfg);
try
{
logging::init_from_stream(file);
}
catch (const std::exception& e)
{
std::cout << "init_logger is fail, read log config file fail. curse: " << e.what() << std::endl;
exit(-2);
}
return true;
}
其实最核心的代码就是logging::init_from_stream这个函数。他能加载你对日志的配置信息。这样比起一般将sink设置,日志级别设置写到代码里面的方式要更加简单。接下来我们来看看配置文件的写法。
配置日志
[Core]
DisableLogging=false
Filter="%Severity% >= trace"
[Sinks.console]
Filter="%Severity% > trace "
Destination=Console
Format="[%TimeStamp%] [%Sever