forked from HardySimpson/zlog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzc_profile.c
86 lines (73 loc) · 1.87 KB
/
zc_profile.c
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* This file is part of the zlog Library.
*
* Copyright (C) 2011 by Hardy Simpson <[email protected]>
*
* Licensed under the LGPL v2.1, see the file COPYING in base directory.
*/
#include "fmacros.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdarg.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include "zc_profile.h"
#include "zc_xplatform.h"
static void zc_time(char *time_str, size_t time_str_size)
{
time_t tt;
struct tm local_time;
time(&tt);
localtime_r(&tt, &local_time);
strftime(time_str, time_str_size, "%m-%d %T", &local_time);
return;
}
int zc_profile_inner(int flag, const char *file, const long line, const char *fmt, ...)
{
va_list args;
char time_str[20 + 1];
FILE *fp = NULL;
static char *debug_log = NULL;
static char *error_log = NULL;
static size_t init_flag = 0;
if (!init_flag) {
init_flag = 1;
debug_log = getenv("ZLOG_PROFILE_DEBUG");
error_log = getenv("ZLOG_PROFILE_ERROR");
}
switch (flag) {
case ZC_DEBUG:
if (debug_log == NULL) return 0;
fp = fopen(debug_log, "a");
if (!fp) return -1;
zc_time(time_str, sizeof(time_str));
fprintf(fp, "%s DEBUG (%d:%s:%ld) ", time_str, getpid(), file, line);
break;
case ZC_WARN:
if (error_log == NULL) return 0;
fp = fopen(error_log, "a");
if (!fp) return -1;
zc_time(time_str, sizeof(time_str));
fprintf(fp, "%s WARN (%d:%s:%ld) ", time_str, getpid(), file, line);
break;
case ZC_ERROR:
if (error_log == NULL) return 0;
fp = fopen(error_log, "a");
if (!fp) return -1;
zc_time(time_str, sizeof(time_str));
fprintf(fp, "%s ERROR (%d:%s:%ld) ", time_str, getpid(), file, line);
break;
}
/* writing file twice(time & msg) is not atomic
* may cause cross
* but avoid log size limit */
va_start(args, fmt);
vfprintf(fp, fmt, args);
va_end(args);
fprintf(fp, "\n");
fclose(fp);
return 0;
}