统一日志的记录格式,用宏调用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_listarg;
    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 );
        return0;
    }
    //log to file
    if( !(fp =fopen( flog,"at" ) ) )  return -1;
    fprintf( fp,"%-32.32s  %s", pre, tmp );
    fclose( fp );
     
    return0;
}

 

调用方法:

LOG_DEFAULT     把日志输出到默认的日志文件

LOG_TOXFILE      把日志输出大指定的日志文件,如果参数是0,则日志打印到标准输出


0 0
原创粉丝点击