12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- #include "stdafx.h"
- #include "Logger.h"
- Logger* SSingleton<Logger>::ms_Singleton = NULL;
- Logger::Logger() {
- // 默认构造函数
- this->target = terminal;
- this->level = debug;
- cout << "[SProxy] " << __FILE__ << " " << currTime() << " : " << "=== Start logging ===" << endl;
- }
- void log_debug_message(const char* format, ...) {
- char logMessage[256];
- va_list args;
- va_start(args, format);
- vsnprintf(logMessage, sizeof(logMessage), format, args);
- va_end(args);
- HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
- SetConsoleTextAttribute(console, FOREGROUND_GREEN); // 设置文本颜色为绿色
- OutputDebugStringA(logMessage);
- SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); // 恢复文本颜色为默认值
- }
- void Logger::Init(log_target target, log_level level, string path)
- {
- this->target = target;
- if (path.empty())
- {
- this->path = std::filesystem::current_path().string() + "\\log\\log.txt";
- }
-
- this->level = level;
- string tmp = ""; // 双引号下的常量不能直接相加,所以用一个string类型做转换
- string welcome_dialog = tmp + "[SProxy] " + __FILE__ + " " + currTime() + " : " + "=== Start logging ===\n";
- if (target != terminal) {
- this->outfile.open(this->path, ios::out | ios::app); // 打开输出文件
- this->outfile << welcome_dialog;
- }
- if (target != file) {
- // 如果日志对象不是仅文件
- cout << welcome_dialog;
- }
- }
-
- void Logger::output(string text, log_level act_level) {
- string prefix;
- if (act_level == debug) prefix = "[DEBUG] ";
- else if (act_level == info) prefix = "[INFO] ";
- else if (act_level == warning) prefix = "[WARNING] ";
- else if (act_level == error) prefix = "[ERROR] ";
- else prefix = "";
- prefix += __FILE__;
- prefix += " ";
- string output_content = prefix + currTime() + " : " + text + "\n";
- if (this->level <= act_level && this->target != file) {
- // 当前等级设定的等级才会显示在终端,且不能是只文件模式
- cout << output_content;
- }
- if (this->target != terminal)
- outfile << output_content;
- #ifdef _DEBUG
- log_debug_message(output_content.c_str());
- #endif // _DEBUG
-
- }
- void Logger::DEBUG(string text) {
- #ifdef _DEBUG
- this->output(text, debug);
- #endif // _DEBUG
-
- }
- void Logger::INFO(string text) {
- this->output(text, info);
- }
- void Logger::WARNING(string text) {
- this->output(text, warning);
- }
- void Logger::LERROR(string text) {
- this->output(text, error);
- }
|