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

81 lines
2.2 KiB
C

12 years ago
#pragma once
#include <string>
#include <chrono>
#include <functional>
12 years ago
#include <sstream>
#include <iomanip>
12 years ago
#include <thread>
12 years ago
#include "common_types.h"
#include "details/os.h"
12 years ago
namespace c11log
{
namespace formatters
{
typedef std::function<std::string(const std::string& logger_name, const std::string&, level::level_enum, const c11log::log_clock::time_point&)> format_fn;
12 years ago
class formatter
{
12 years ago
public:
formatter() {}
virtual ~formatter() {}
virtual void format_header(const std::string& logger_name, level::level_enum level, const log_clock::time_point& tp, std::ostream& dest) = 0;
12 years ago
};
class default_formatter: public formatter
{
12 years ago
public:
// Format: [2013-12-29 01:04:42.900] [logger_name:Info] Message body
void format_header(const std::string& logger_name, level::level_enum level, const log_clock::time_point& tp, std::ostream& dest) override {
12 years ago
_format_time(tp, dest);
if(!logger_name.empty())
dest << " [" << logger_name << ":" << c11log::level::to_str(level) << "] ";
else
dest << " [" << c11log::level::to_str(level) << "] ";
12 years ago
}
12 years ago
private:
void _format_time(const log_clock::time_point& tp, std::ostream &dest);
12 years ago
};
} //namespace formatter
} //namespace c11log
12 years ago
inline void c11log::formatters::default_formatter::_format_time(const log_clock::time_point& tp, std::ostream &dest)
{
12 years ago
#ifdef _MSC_VER
__declspec(thread) static std::tm last_tm = { 0, 0, 0, 0, 0, 0, 0, 0, 0};
__declspec(thread) static char last_time_str[64];
#else
thread_local static std::tm last_tm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
thread_local static char last_time_str[64];
12 years ago
#endif
12 years ago
auto tm_now = details::os::localtime(log_clock::to_time_t(tp));
using namespace c11log::details::os;
if(last_tm != tm_now) {
12 years ago
#ifdef _MSC_VER
::sprintf_s
#else
::snprintf
12 years ago
#endif
(last_time_str, sizeof(last_time_str), "[%d-%02d-%02d %02d:%02d:%02d]",
tm_now.tm_year + 1900,
tm_now.tm_mon + 1,
tm_now.tm_mday,
tm_now.tm_hour,
tm_now.tm_min,
tm_now.tm_sec);
12 years ago
last_tm = tm_now;
}
dest << last_time_str;
12 years ago
}