超级简单的日志模块
windows
linux 下需要 实现 GetPrivateProfileString
头文件 mylog.h
#ifndef MY_LOG_H #ifdef MY_LOG_H #pragma once #include <iostream> #include <list> #include <stdlib.h> #include <stdio.h> #include <string> #include <vector> #include <fstream> #include <sstream> #include <mutex> #include <Windows.h> std::mutex s_logfile_mtx; enum Loglv { DEGUG_LEVEL = 0, ERROR_LEVEL = 1 }; void my_log_file(const char* filename, int line, Loglv level, const char* msg, ...); #define LOGDEBUG(msg, ...) my_log_file(__FILE__, __LINE__, DEGUG_LEVEL, msg, __VA_ARGS__) #define LOGERROR(msg, ...) my_log_file(__FILE__, __LINE__, ERROR_LEVEL, msg, __VA_ARGS__)
mylog.cpp
#include "mylog.h" void my_log_file(const char* filename, int line, Loglv level, const char* msg, ...) REQUIRES(!s_logfile_mtx) { if (msg == nullptr) return; auto pid = GetCurrentProcessId(); auto inipath = "test.ini".u8string(); std::array<WCHAR, 20480> content = {}; std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); std::time_t now_time_t = std::chrono::system_clock::to_time_t(now); std::tm now_tm {}; ::localtime_s(&now_tm, &now_time_t); char datetime[20] {}; char tdatetime[20] {}; va_list args; va_start(args, msg); char buffer[20480] = {0}; vsnprintf(buffer, sizeof(buffer), msg, args); strftime(datetime, sizeof(datetime), "%Y-%m-%d %H:%M:%S", &now_tm); if (level == DEGUG_LEVEL) { GetPrivateProfileString(TEXT("LOG"), TEXT("FLAG"), TEXT(""), content.data(), 20479, str2ws(inipath).c_str()); if (content[0] != L'1') return; } auto logfilepath = "./MGFastTransfer.log".u8string(); if (std::filesystem::exists(logfilepath)) { auto fileSize = GetFileSize(logfilepath); if (fileSize > static_cast<size_t>(5 * 1024) * 1024) { strftime(tdatetime, sizeof(tdatetime), "%Y%m%d%H%M%S", &now_tm); auto newlogfilepath = "test.log" + std::string(tdatetime)).u8string(); std::filesystem::rename(logfilepath, newlogfilepath); } } if (!std::filesystem::exists("log")) { std::filesystem::create_directory("log"); } std::lock_guard(s_logfile_mtx); // 加锁操作 std::ofstream file(str2ws(logfilepath), std::ios::app); if (!file.is_open()) { return; } file << std::string(datetime) + " 文件名:" + std::string(filename) + " 行号:" + std::to_string(line) + " 进程号:" + std::to_string(pid) + " 日志级别:" + std::to_string(level) + " 日志信息:" + buffer + "\n"; file.close(); #endif } #endif
test.c
#include "mylog.h" int main(){ LOGERROR("测试%s|%d", "测试", 10); return 0; }