/*] Copyright (c) 2009-2011, Charles McGarvey [***************************** **] All rights reserved. * * Distributable under the terms and conditions of the 2-clause BSD license; * see the file COPYING for a complete text of the license. * *****************************************************************************/ #if HAVE_INCLUDE_H #include "config.h" #endif #include #if PLATFORM_POSIX #include #else inline int isatty(int dummy) { return 0; } #endif #include "log.hh" #include "script.hh" namespace moof { enum log::level log::global_level_ = log::info; void log::level(enum level level) { global_level_ = level; } enum log::level log::level() { return global_level_; } log::log(enum level level) : level_(level) { if (isatty(1) == 0) switch (level) { case log::error: prefix_ = " error: "; break; case log::warning: prefix_ = "warning: "; break; case log::info: prefix_ = " info: "; break; case log::debug: prefix_ = " debug: "; break; case log::none: break; } else switch (level) { case log::error: prefix_ = "\033[30;101m error: "; break; case log::warning: prefix_ = "\033[30;103mwarning: "; break; case log::info: prefix_ = " info: "; break; case log::debug: prefix_ = "\033[2m debug: "; case log::none: break; } } std::ostream& operator << (class log& log, log::endl_ endl) { if (log::global_level_ < log.level_) return null_log; if (isatty(1) == 0) return moof::log << std::endl; return moof::log << "\033[0m" << std::endl; } std::ostream& operator << (std::ostream& stream, log::endl_ endl) { if (isatty(1) == 0) return stream << std::endl; return stream << "\033[0m" << std::endl; } std::ostream& log(std::cout); static std::ofstream null_log_; std::ostream& null_log(null_log_); // These objects are intentionally not deconstructed so that logging will // still be available after this module has been cleaned up. class log& log_error(*new class log(log::error)); class log& log_warning(*new class log(log::warning)); class log& log_info(*new class log(log::info)); class log& log_debug(*new class log(log::debug)); static int log_script(script& script, enum log::level level) { static class log* logs[] = { 0, &log_error, &log_warning, &log_info, &log_debug }; script::slot param = script[1]; while (!param.is_none()) { (*logs[level])(param); ++param.index; } return 0; } void log::import(script& script) { script.import_function("LogError", boost::bind(log_script, _1, log::error)); script.import_function("LogWarning", boost::bind(log_script, _1, log::warning)); script.import_function("LogInfo", boost::bind(log_script, _1, log::info)); script.import_function("print", boost::bind(log_script, _1, log::info)); script.import_function("LogDebug", boost::bind(log_script, _1, log::debug)); } } // namespace moof