搞了好久搞出来的代码
# include <iostream>
# include <fstream>
# include <chrono>
# include <ctime>
# include <cstdarg> # define LOG_TO_CONSOLE_AND_FILE_WITH_DATE
# ifdef LOG_TO_CONSOLE_AND_FILE_WITH_DATE
# define LOG ( format, . . . ) LogToConsoleAndFile ( "log.txt" , true , format, __VA_ARGS__)
# elif defined ( LOG_TO_CONSOLE_AND_FILE)
# define LOG ( format, . . . ) LogToConsoleAndFile ( "log.txt" , false , format, __VA_ARGS__)
# else
# define LOG ( format, . . . ) LogToConsole ( format, __VA_ARGS__)
# endif void LogToConsole ( const char * format, . . . )
{ va_list args; va_start ( args, format) ; vprintf ( format, args) ; va_end ( args) ;
} void LogToConsoleAndFile ( const std:: string& filename, bool includeDate, const char * format, . . . )
{ std:: ofstream file ( filename, std:: ios:: app) ; if ( ! file. is_open ( ) ) { std:: cerr << "无法打开日志文件:" << filename << std:: endl; return ; } auto now = std:: chrono:: system_clock:: now ( ) ; std:: time_t currentTime = std:: chrono:: system_clock:: to_time_t ( now) ; std:: tm timeInfo;
# ifdef _WIN32 localtime_s ( & timeInfo, & currentTime) ;
# else localtime_r ( & currentTime, & timeInfo) ;
# endif char timeBuffer[ 128 ] ; if ( includeDate) { std:: strftime ( timeBuffer, sizeof ( timeBuffer) , "%Y-%m-%d %T" , & timeInfo) ; } else { std:: strftime ( timeBuffer, sizeof ( timeBuffer) , "%T" , & timeInfo) ; } va_list args; va_start ( args, format) ; char buffer[ 256 ] ; vsnprintf ( buffer, sizeof ( buffer) , format, args) ; va_end ( args) ; std:: printf ( "%s %s\n" , timeBuffer, buffer) ; file << timeBuffer << " " << buffer << std:: endl;
} int main ( )
{ int line = 23 ; int index = 1 ; int x{ 435 } , y{ 334 } ; LOG ( "---%d行------窗口:%d-----------坐标:%d,%d--------" , line, index, x, y) ; return 0 ;
}