#include "log.h" #include #include #include #include #include #include #include #include #include #include #include namespace dt = boost::posix_time; namespace logging = boost::log; namespace logexpr = boost::log::expressions; #ifdef USING_ASYNC_LOG_MODE typedef logging::sinks::asynchronous_sink sink_t; #else typedef logging::sinks::synchronous_sink sink_t; #endif // USING_ASYNC_LOG_MODE // variables static logging::sources::severity_channel_logger_mt lg = logging::sources::severity_channel_logger_mt(logging::keywords::channel = "net"); static boost::shared_ptr sink = nullptr; static logging::attributes::mutable_constant rotation_date = logging::attributes::mutable_constant(dt::to_iso_extended_string(dt::second_clock::local_time() + dt::hours(4)).substr(0, 10)); #define logger_trace BOOST_LOG_SEV(lg,logging::trivial::severity_level::trace) #define logger_debug BOOST_LOG_SEV(lg,logging::trivial::severity_level::debug) #define logger_info BOOST_LOG_SEV(lg,logging::trivial::severity_level::info) #define logger_warning BOOST_LOG_SEV(lg,logging::trivial::severity_level::warning) #define logger_error BOOST_LOG_SEV(lg,logging::trivial::severity_level::error) #define logger_fatal BOOST_LOG_SEV(lg,logging::trivial::severity_level::fatal) bool logger::init(std::string strLogPath, std::string strLogName) { // 初始化日志 logging::add_common_attributes(); boost::shared_ptr core = logging::core::get(); core->add_global_attribute("RotationDate", rotation_date); boost::shared_ptr backend = boost::make_shared(); // Set up the file naming pattern boost::gregorian::date d(boost::gregorian::day_clock::local_day()); backend->set_file_name_composer(logging::sinks::file::as_file_name_composer( logexpr::stream << strLogPath << "/" << boost::gregorian::to_iso_string(d) << "_" // 文件名还是带上Level,否者copy到一起的时候分不清 << logexpr::attr("Severity") << "_" << strLogName << ".log")); sink = boost::shared_ptr(new sink_t(backend)); // Set the formatter sink->set_formatter(logexpr::stream << "datetime=" << logexpr::format_date_time("TimeStamp", "%Y-%m-%d %H:%M:%S.%f") << logexpr::smessage); core->add_sink(sink); return true; } void logger::update_rotation_time() { dt::ptime t = dt::second_clock::local_time(); if (t.time_of_day().hours() <= 20) return; t += dt::hours(4); // 以20点为界切割一个交易日,选择20的原因是这样使得所有的数据可以用一天表示,原油也可以 rotation_date.set(dt::to_iso_extended_string(t).substr(0, 10)); } void logger::showLog(std::string msg) { logger_info << msg; } void logger::stop() { if (sink == nullptr) return; boost::shared_ptr core = logging::core::get(); core->remove_sink(sink); #ifdef USING_ASYNC_LOG_MODE sink->stop(); #endif // USING_ASYNC_LOG_MODE sink->flush(); sink.reset(); }