| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- //
- // logger.cpp
- // logger
- //
- // Created by Sam Jaffe on 9/3/16.
- //
- #include <sys/time.h>
- #include <cassert>
- #include <cmath>
- #include <ctime>
- #include <map>
- #include <stdexcept>
- #include "expect/expect.hpp"
- #include "logger.hpp"
- #include "properties.hpp"
- namespace logging {
- #define X(l) \
- case logging::L##l: \
- return #l;
-
- const char* level_header(log_level l) {
- assert(l != logging::LNONE);
- switch (l) {
- X(FATAL)
- X(CRITICAL)
- X(ERROR)
- X(WARNING)
- X(INFO)
- X(DEBUG)
- X(TRACE)
- X(NONE)
- }
- }
-
- #undef X
- }
- namespace {
- struct timeval now( ) {
- struct timeval tv;
- gettimeofday( &tv, nullptr );
- return tv;
- }
- }
- namespace logging {
- class multiple_bindings : public std::logic_error {
- using std::logic_error::logic_error;
- };
-
- // extern logger_impl& _logger_impl_shared_instance();
- extern _binding _default_logger_impl;
- static _binding _impl_binding = nullptr;
-
- bool bind_logger_impl(_binding impl) {
- expects(_impl_binding == nullptr, multiple_bindings,
- "Only one logger implementation may be bound");
- _impl_binding = impl;
- return true;
- }
-
- logger_impl& _i_get_shared_instance() {
- if (_impl_binding == nullptr) {
- return _default_logger_impl();
- } else {
- return _impl_binding();
- }
- }
- }
- namespace logging {
- logger& logger::instance() {
- static logger instance;
- return instance;
- }
-
- logger& logger::instance(std::string const & name) {
- using p_logger = std::unique_ptr<logger>;
- using store = std::map<std::string, p_logger>;
- static store instances;
- store::iterator it;
- if ((it = instances.find(name)) != instances.end()) {
- return *(it->second);
- }
- return *(instances.emplace(std::make_pair(name, p_logger(new logger(name)))).first->second);
- }
-
-
- logger::logger(std::string const & name)
- : min_level_(LDEBUG)
- , logger_name_(name)
- , impl_(_i_get_shared_instance())
- {
- }
-
- logger::~logger() {
- flush();
- }
-
- void logger::log(log_level ll, location_info info, std::string const & msg) {
- impl_.write({ now( ), ll, info, logger_name_.c_str(), msg });
- }
-
- bool logger::should_log( log_level ll ) const {
- return ll < min_level_ && impl_.should_log( ll );
- }
-
- void logger::flush() {
- impl_.flush();
- }
- }
- namespace logging {
-
- bool logger_impl::should_log( log_level ll ) const {
- return ll < min_log_level;
- }
- }
- void test() {
- logging::logger & LOG = logging::logger::instance( );
- LOG.log(logging::LERROR, "{}", 5);
- }
|