统一日志的记录格式,用宏调用printf
来源:互联网 发布:gif制作软件中文版 编辑:程序博客网 时间:2024/05/18 03:41
http://www.cnblogs.com/linxr/archive/2010/11/12/1927002.html
软件一般都要输出日志,方便排错和跟踪运行情况。所有日志文件的格式还是要美化点好,以免在查找关键信息时费时费力。
所以日志函数要支持:
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,则日志打印到标准输出
0 0
- 统一日志的记录格式,用宏调用printf
- 统一的日志调用接口 SLF4j
- printf记录程序日志
- 【Java进阶】利用APT优雅的实现统一日志格式
- printf格式化输出中要输出的格式与输入的变量格式不统一的问题
- Linux环境下用printf做彩色日志记录
- printf 的打印格式
- printf的格式输出
- printf的格式说明
- Printf的格式
- printf()的格式
- printf的打印格式
- printf( )的格式字符
- printf支持的格式
- printf( )的格式字符
- printf的格式控制
- printf记录程序日志,彻底告别vsnprintf
- printf记录程序日志,彻底告别vsnprintf
- Cobol License Manager Error; 'Unable to open License Key database'
- OC语言--内存管理
- 论优秀程序员需要的品/质
- DLAN初步了解
- 剑指offer 面试题15 找到单链表倒数第k个结点
- 统一日志的记录格式,用宏调用printf
- Android开发网上的一些重要知识点 [2]
- 【实习设计三】为什么使用spring
- 第一章结构图
- 栈ADT
- Google Protocol Buffers浅析
- linux2.6.x和linux3.0
- Linux Shell——-if -eq,if -ne,if -gt[笔记]
- 模拟电子表的功能