统一日志的记录格式,用宏调用printf
软件一般都要输出日志,方便排错和跟踪运行情况。所有日志文件的格式还是要美化点好,以免在查找关键信息时费时费力。
所以日志函数要支持:
1、时间和地点。即什么时候哪个地方报的信息。
2、为了方便调用,必须支持多重格式的输出,所以使用printf的格式是最好的。
下面就是我写的一个日志函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #include <stdarg.h> #include <stdio.h> #include <time.h> #define LOG_FILE "./a.log" #define LOG_DEFAULT( fmt, ... ) log_out( LOG_FILE, __FILE__, __LINE__, fmt, ##__VA_ARGS__) #define LOG_TOXFILE( flog, fmt, ... ) log_out( flog, __FILE__, __LINE__, fmt, ##__VA_ARGS__) int log_out( char * flog, char *file, int line, char * fmt, ...) { va_list arg; char pre[128], tmp[1024]; long clock ; struct tm *c_ptr; FILE *fp; time ( & clock ); c_ptr = localtime (& clock ); sprintf ( pre, "[%04d%02d%02d%02d%02d%02d_%s.%d]" , c_ptr->tm_year+1900, c_ptr->tm_mon+1, c_ptr->tm_mday, c_ptr->tm_hour, c_ptr->tm_min, c_ptr->tm_sec, file, line ); va_start (arg, fmt); vsprintf (tmp, fmt, arg); va_end (arg); //log to stdout if ( !flog ){ printf ( "%-32.32s %s" , pre, tmp ); return 0; } //log to file if ( !(fp = fopen ( flog, "at" ) ) ) return -1; fprintf ( fp, "%-32.32s %s" , pre, tmp ); fclose ( fp ); return 0; } |
调用方法:
LOG_DEFAULT 把日志输出到默认的日志文件
LOG_TOXFILE 把日志输出大指定的日志文件,如果参数是0,则日志打印到标准输出
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库