You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
spdlog/include/c11log/formatter.h

91 lines
2.5 KiB
C

12 years ago
#pragma once
#include <string>
#include <chrono>
#include <functional>
12 years ago
#include <iomanip>
#include <thread>
#include <cstring>
11 years ago
#include <sstream>
12 years ago
#include "common_types.h"
#include "details/os.h"
11 years ago
12 years ago
namespace c11log
{
namespace formatters
{
class formatter
{
12 years ago
public:
virtual void format_header(const std::string& logger_name, level::level_enum level, const log_clock::time_point& tp, std::ostream& output) = 0;
12 years ago
};
class default_formatter: public formatter
{
public:
// Format: [2013-12-29 01:04:42.900] [logger_name:Info] Message body
12 years ago
void format_header(const std::string& logger_name, level::level_enum level, const log_clock::time_point& tp, std::ostream& output) override
12 years ago
{
12 years ago
_format_time(tp, output);
12 years ago
if(!logger_name.empty())
12 years ago
output << " [" << logger_name << ':' << c11log::level::to_str(level) << "] ";
12 years ago
else
12 years ago
output << " [" << c11log::level::to_str(level) << "] ";
12 years ago
}
private:
12 years ago
void _format_time(const log_clock::time_point& tp, std::ostream &output);
12 years ago
};
} //namespace formatter
} //namespace c11log
// Format datetime like this: [2014-03-14 17:15:22]
12 years ago
inline void c11log::formatters::default_formatter::_format_time(const log_clock::time_point& tp, std::ostream &output)
12 years ago
{
using namespace c11log::details::os;
using namespace std::chrono;
#ifdef _WIN32 //VS2013 doesn't support yet thread_local keyword
__declspec(thread) static char s_cache_str[64];
__declspec(thread) static size_t s_cache_size;
__declspec(thread) static std::time_t s_cache_time_t = 0;
#else
11 years ago
thread_local static std::string s_cache_timestr;
12 years ago
thread_local static std::time_t s_cache_time_t = 0;
#endif
//Cache every second
std::time_t tp_time_t = log_clock::to_time_t(tp);
if(tp_time_t != s_cache_time_t)
{
auto tm_now = details::os::localtime(tp_time_t);
11 years ago
std::ostringstream time_oss;
12 years ago
time_oss.fill('0');
time_oss << '[' << tm_now.tm_year + 1900 << '-';
time_oss.width(2);
time_oss << tm_now.tm_mon + 1 << '-';
time_oss.width(2);
time_oss << tm_now.tm_mday << ' ';
time_oss.width(2);
time_oss << tm_now.tm_hour << ':';
time_oss.width(2);
time_oss << tm_now.tm_min << ':';
time_oss.width(2);
time_oss << tm_now.tm_sec << ']';
//Cache the resulted string and its size
s_cache_time_t = tp_time_t;
11 years ago
//const std::string &s = time_oss.str_ref();
s_cache_timestr = time_oss.str();
12 years ago
}
11 years ago
output << s_cache_timestr;
12 years ago
}