spdlog/include/c11log/formatter.h

65 lines
1.9 KiB
C
Raw Normal View History

2014-01-25 17:09:04 +08:00
#pragma once
2014-03-01 20:06:58 +08:00
#include <string>
#include <chrono>
#include <functional>
2014-01-25 17:09:04 +08:00
#include <sstream>
2014-03-01 20:06:58 +08:00
#include <iomanip>
2014-03-04 07:23:38 +08:00
#include <thread>
2014-01-25 17:09:04 +08:00
2014-03-01 20:06:58 +08:00
#include "common_types.h"
2014-02-22 07:16:59 +08:00
#include "details/os.h"
2014-01-25 17:09:04 +08:00
namespace c11log {
namespace formatters {
2014-03-01 20:06:58 +08:00
typedef std::function<std::string(const std::string& logger_name, const std::string&, level::level_enum, const c11log::log_clock::time_point&)> format_fn;
2014-02-12 03:03:57 +08:00
2014-01-25 17:09:04 +08:00
std::string to_hex(const unsigned char* buf, std::size_t size);
class formatter {
public:
formatter() {}
virtual ~formatter() {}
2014-03-01 20:06:58 +08:00
virtual void format_header(const std::string& logger_name, level::level_enum level, const log_clock::time_point& tp, std::ostream& dest) = 0;
2014-01-25 17:09:04 +08:00
};
class default_formatter: public formatter {
public:
// Format: [2013-12-29 01:04:42.900] [logger_name:Info] Message body
2014-03-01 20:06:58 +08:00
void format_header(const std::string& logger_name, level::level_enum level, const log_clock::time_point& tp, std::ostream& dest) override {
2014-02-12 03:03:57 +08:00
_format_time(tp, dest);
2014-01-25 17:09:04 +08:00
dest << " [" << logger_name << ":" << c11log::level::to_str(level) << "] ";
}
2014-02-12 03:03:57 +08:00
private:
2014-03-01 20:06:58 +08:00
void _format_time(const log_clock::time_point& tp, std::ostream &dest);
2014-01-25 17:09:04 +08:00
};
} //namespace formatter
} //namespace c11log
2014-02-21 03:39:58 +08:00
2014-03-01 20:06:58 +08:00
inline void c11log::formatters::default_formatter::_format_time(const log_clock::time_point& tp, std::ostream &dest)
2014-03-02 22:31:13 +08:00
{
2014-03-04 07:23:38 +08:00
__declspec(thread) static std::tm last_tm = { 0, 0, 0, 0, 0, 0, 0, 0, 0};
__declspec(thread) static char last_time_str[64];
auto tm_now = details::os::localtime(log_clock::to_time_t(tp));
2014-03-04 07:23:38 +08:00
if(last_tm != tm_now)
2014-03-04 07:23:38 +08:00
{
sprintf(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);
2014-03-04 07:23:38 +08:00
last_tm = tm_now;
}
dest << last_time_str;
2014-02-21 03:39:58 +08:00
}