#include "Sink.h" #include "lib/logging/logging.h" #include "lib/os/os.h" #include "lib/utils/datetime.h" #include "lib/utils/file_utils.h" #include "lib/utils/bts_assert.h" #include #include #include #include #include #include #ifndef WIN32 #include #endif namespace bts { namespace log { struct InitSysLog { InitSysLog() { #ifndef WIN32 openlog("spark",0,LOG_USER); #endif } } init; auto formatter() { return [] (LogMsg const&m) { auto iso_date = datetime::iso_date_time_string(datetime::local_now()); iso_date[sizeof("YYYY-MM-DD")-1] = ' '; return fmt::format("{}|{}|{:<8}|{:<5}|{:<3}|{:<16}|{:<4}|{:<35}|{} ", iso_date, m.ts, m.subsystem_name, m.level_name, m.tid, m.thread_name, os::process_id(), fmt::format("{}:{}",boost::filesystem::path(m.file).filename().string() , m.line), m.msg); }; } Sink console_sink() { auto f = formatter(); return [f] (LogMsg const &m) {std::cout << f(m) << std::endl;}; } Sink syslog_sink() { #ifdef WIN32 return null_sink(); #else auto f = formatter(); return [f] (LogMsg const &m) {syslog (LOG_INFO | LOG_USER,"%s",f(m).c_str ());}; #endif } std::ifstream::pos_type filesize(std::string const&filename) { if(!boost::filesystem::exists(filename)) return 0; else { std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary); return in.tellg(); } } Sink file_sink() { static std::ofstream stream; static uint64_t bytes_written = 0; const auto max_sz = 120 * 1024 * 1024; auto f= formatter(); auto path = log_path(); path /= "log"; auto parent = path.parent_path(); if (!boost::filesystem::is_directory(parent)) bts_assert(boost::filesystem::create_directories(parent)); if(boost::filesystem::exists(path)) { auto sz = boost::filesystem::file_size(path); if (sz > max_sz) { auto backup = boost::filesystem::path(path.string() + ".old"); boost::filesystem::rename(path, backup); } } stream = std::ofstream(path.string(),std::ofstream::app); return [=] (LogMsg const &m) { auto msg = f(m); bytes_written += msg.size(); if (bytes_written >= max_sz) { bytes_written = 0; stream.close(); auto backup = boost::filesystem::path(path.string() + ".old"); boost::filesystem::rename(path, backup); stream = std::ofstream(path.string(),std::ofstream::app); } stream << f(m) << std::endl; }; } Sink null_sink() { return [](const LogMsg&) {}; } }}