文章目录
- 0. 引言
- 1. python
- 2. c++
0. 引言
本文主要记录python版本和c++版本常用的日志基础示例。
1. python
python版本常用的是logging库,结合colorlog库,可根据不同日志级别打印不同颜色的日志,为了便于分析问题,还添加了日志保存到文件的设置,默认保存到代码运行目录的logs/时间戳
目录下,代码示例如下:
import logging
import colorlog
import os
from datetime import datetimeclass ColorLogger:SUCCESS_LEVEL_NUM = 25def __init__(self, name='app_logger', log_dir='logs', level=logging.DEBUG):# 定义 SUCCESS 级别logging.addLevelName(self.SUCCESS_LEVEL_NUM, "SUCCESS")# 创建日志目录if not os.path.exists(log_dir):os.makedirs(log_dir)# 创建带时间戳的子目录timestamp = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")log_folder = os.path.join(log_dir, timestamp)os.makedirs(log_folder)# 日志文件路径log_file = os.path.join(log_folder, 'app.log')# 自定义日志记录方法def success(self, message, *args, **kwargs):if self.isEnabledFor(ColorLogger.SUCCESS_LEVEL_NUM):self._log(ColorLogger.SUCCESS_LEVEL_NUM, message, args, **kwargs)# 将自定义方法绑定到 Logger 类logging.Logger.success = success# 创建 logger 对象self.logger = logging.getLogger(name)self.logger.setLevel(level)# 创建控制台 handlerconsole_handler = colorlog.StreamHandler()console_formatter = colorlog.ColoredFormatter("%(log_color)s%(asctime)s - %(levelname)s - %(message)s",log_colors={'DEBUG': 'blue','INFO': '','WARNING': 'yellow','ERROR': 'red','CRITICAL': 'bold_red','SUCCESS': 'green'})console_handler.setFormatter(console_formatter)self.logger.addHandler(console_handler)# 创建文件 handlerfile_handler = logging.FileHandler(log_file)file_handler.setLevel(level)file_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')file_handler.setFormatter(file_formatter)self.logger.addHandler(file_handler)def debug(self, message):self.logger.debug(message)def info(self, message):self.logger.info(message)def warning(self, message):self.logger.warning(message)def error(self, message):self.logger.error(message)def critical(self, message):self.logger.critical(message)def success(self, message):self.logger.success(message)# 实例化示例
if __name__ == "__main__":logger = ColorLogger()test = "1234567890"# 记录各种级别的日志logger.info(f"这是测试信息 {test}")logger.debug("这是调试信息 (DEBUG)")logger.info("这是普通信息 (INFO)")logger.warning("这是警告信息 (WARNING)")logger.error("这是错误信息 (ERROR)")logger.critical("这是严重错误信息 (CRITICAL)")logger.success("这是成功信息 (SUCCESS)")
运行结果:
2. c++
c++也可以实现类似的效果,main.cpp
代码如下:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <ctime>
#include <sstream>
#include <filesystem>class ColorLogger {
public:enum LogLevel { DEBUG, INFO, WARNING, ERROR, CRITICAL, SUCCESS };ColorLogger(const std::string& name = "app_logger", const std::string& logDir = "logs"): loggerName(name), logDirectory(logDir) {// 创建日志目录if (!std::filesystem::exists(logDirectory)) {std::filesystem::create_directory(logDirectory);}// 创建带时间戳的子目录std::string timestamp = getCurrentTimestamp();logFolder = logDirectory + "/" + timestamp;std::filesystem::create_directory(logFolder);// 日志文件路径logFile = logFolder + "/app.log";logStream.open(logFile, std::ios::app);}~ColorLogger() {if (logStream.is_open()) {logStream.close();}}void log(LogLevel level, const std::string& message) {std::string prefix = getLogLevelString(level);std::cout << prefix << message << std::endl; // 输出到控制台if (logStream.is_open()) {logStream << prefix << message << std::endl; // 写入到文件}}void debug(const std::string& message) {log(DEBUG, message);}void info(const std::string& message) {log(INFO, message);}void warning(const std::string& message) {log(WARNING, message);}void error(const std::string& message) {log(ERROR, message);}void critical(const std::string& message) {log(CRITICAL, message);}void success(const std::string& message) {log(SUCCESS, message);}private:std::string loggerName;std::string logDirectory;std::string logFolder;std::string logFile;std::ofstream logStream;std::string getCurrentTimestamp() {auto now = std::time(nullptr);std::tm tm = *std::localtime(&now);std::ostringstream oss;oss << std::put_time(&tm, "%Y%m%d_%H%M%S");return oss.str();}std::string getLogLevelString(LogLevel level) {switch (level) {case DEBUG: return "\033[34m[DEBUG] \033[0m"; // 蓝色case INFO: return "\033[0m[INFO] \033[0m"; // 默认颜色case WARNING: return "\033[33m[WARNING] \033[0m"; // 黄色case ERROR: return "\033[31m[ERROR] \033[0m"; // 红色case CRITICAL:return "\033[41m[CRITICAL] \033[0m"; // 红色背景case SUCCESS: return "\033[32m[SUCCESS] \033[0m"; // 绿色default: return "\033[0m[UNKNOWN] \033[0m"; // 默认颜色}}
};// 实例化示例
int main() {ColorLogger logger;// 记录各种级别的日志logger.debug("这是调试信息 (DEBUG)");logger.info("这是普通信息 (INFO)");logger.warning("这是警告信息 (WARNING)");logger.error("这是错误信息 (ERROR)");logger.critical("这是严重错误信息 (CRITICAL)");logger.success("这是成功信息 (SUCCESS)");return 0;
}
对应的CMakeLists.txt
如下:
cmake_minimum_required(VERSION 3.10)# 设置项目名称和版本
project(ColorLoggerProject VERSION 1.0)# 指定 C++ 标准
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)# 添加可执行文件
add_executable(ColorLogger main.cpp)
mkdir build
cd build
make -j8
# 执行
./ColorLogger
运行结果:
当然,c++也有现成的库,比如glog,spdlog等,常用的是glog,示例代码如下:
需要先安装glog (推荐源码编译):
git clone https://github.com/google/glog.git
cd glog
mkdir build
cd build
cmake ..
make
main.cpp代码示例:
#include <glog/logging.h>
#include <iostream>
#include <string>int main(int argc, char* argv[]) {// 初始化 Google Logginggoogle::InitGoogleLogging(argv[0]);FLAGS_log_dir = "logs";std::string test = "1234567890";LOG(INFO) << "这是测试信息 " << test; // 普通信息LOG(WARNING) << "这是警告信息"; // 警告信息LOG(ERROR) << "这是错误信息"; // 错误信息// LOG(FATAL) << "这是致命错误信息"; // 致命错误(程序会终止)google::ShutdownGoogleLogging();return 0;
}
对应的CMakeLists.txt :common_lib_path 替换成自己编译的glob路径
cmake_minimum_required(VERSION 3.10)project(GlogExample)# 指定 C++ 标准
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)set(common_lib_path "/nvme/PLITOE/common_lib")include_directories(${common_lib_path}/include)link_directories(${common_lib_path}/lib)# 添加可执行文件
add_executable(glog_example main.cpp)# 链接 glog 库
target_link_libraries(glog_example glog)
mkdir build
cd build
make -j8
# 执行,可先在当前文件夹下 mkdir logs
./glog_example
执行后,可在logs中看到各种级别的日志文件。
⭐️👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍🌔