Files
spark/src/lib/logging/Sink.cpp
T

132 lines
3.0 KiB
C++

#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 <fmt/ostream.h>
#include <fstream>
#include <iostream>
#include <boost/filesystem/path.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem.hpp>
#ifdef WIN32
#include <Windows.h>
#else
#include <syslog.h>
#endif
namespace bts {
namespace log {
#ifdef WIN32
HANDLE win_event_log;
#endif
struct InitSysLog {
InitSysLog() {
#ifdef WIN32
win_event_log = RegisterEventSource(NULL,"spark");
#else
openlog("spark",0,LOG_USER);
#endif
}
} init;
auto formatter() {
return [] (LogMsg const&m) {
return fmt::format("{}: {} | ~{}:{}~ {}:{} tid:{} pid:{}",
datetime::time_string(datetime::now()),
m.msg,
m.subsystem_name,
m.level_name,
boost::filesystem::path(m.file).filename().string() ,
m.line,
m.tid,
os::process_id());
};
}
Sink console_sink() {
auto f = formatter();
return [f] (LogMsg const &m) {std::cout << f(m) << std::endl;};
}
Sink syslog_sink() {
auto f = formatter();
#ifdef WIN32
return [f] (LogMsg const &m) {
int win_level;
switch (m.level.ordinal) {
case 0:
win_level = EVENTLOG_SUCCESS;
break;
case 1:
win_level = EVENTLOG_INFORMATION_TYPE;
break;
case 2:
win_level = EVENTLOG_WARNING_TYPE;
break;
default:
win_level = EVENTLOG_ERROR_TYPE;
break;
};
auto str = f(m).c_str();
ReportEvent(win_event_log,win_level,0,0,NULL,1,0,&str,0);
};
#else
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();
}
}
boost::filesystem::path log_path ()
{
auto store_root = os::bts_data_path();
std::string base_path = store_root;
boost::filesystem::path result = utils::normalize_data_path (base_path);
result /= "logging";
result /= "log";
return result;
}
Sink file_sink() {
auto f= formatter();
auto path = log_path();
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 > 120 * 1024 * 1024) {
auto backup = boost::filesystem::path(path.string() + ".old");
boost::filesystem::rename(path, backup);
}
}
auto stream = new std::ofstream(path.string(),std::ofstream::app);
return [f,stream] (LogMsg const &m) {*stream << f(m) << std::endl;};
}
}}