1 /*
2 * This file is part of the zlog Library.
3 *
4 * Copyright (C) 2011 by Hardy Simpson <HardySimpson1984@gmail.com>
5 *
6 * Licensed under the LGPL v2.1, see the file COPYING in base directory.
7 */
8
9 #include "fmacros.h"
10
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdlib.h>
14 #include <errno.h>
15 #include <stdarg.h>
16 #include <time.h>
17 #include <sys/types.h>
18 #include <unistd.h>
19
20 #include "zc_profile.h"
21 #include "zc_xplatform.h"
22
zc_time(char * time_str,size_t time_str_size)23 static void zc_time(char *time_str, size_t time_str_size)
24 {
25 time_t tt;
26 struct tm local_time;
27
28 time(&tt);
29 localtime_r(&tt, &local_time);
30 strftime(time_str, time_str_size, "%m-%d %T", &local_time);
31
32 return;
33 }
34
zc_profile_inner(int flag,const char * file,const long line,const char * fmt,...)35 int zc_profile_inner(int flag, const char *file, const long line, const char *fmt, ...)
36 {
37 va_list args;
38 char time_str[20 + 1];
39 FILE *fp = NULL;
40
41 static char *debug_log = NULL;
42 static char *error_log = NULL;
43 static size_t init_flag = 0;
44
45 if (!init_flag) {
46 init_flag = 1;
47 debug_log = getenv("ZLOG_PROFILE_DEBUG");
48 error_log = getenv("ZLOG_PROFILE_ERROR");
49 }
50
51 switch (flag) {
52 case ZC_DEBUG:
53 if (debug_log == NULL) return 0;
54 fp = fopen(debug_log, "a");
55 if (!fp) return -1;
56 zc_time(time_str, sizeof(time_str));
57 fprintf(fp, "%s DEBUG (%d:%s:%ld) ", time_str, getpid(), file, line);
58 break;
59 case ZC_WARN:
60 if (error_log == NULL) return 0;
61 fp = fopen(error_log, "a");
62 if (!fp) return -1;
63 zc_time(time_str, sizeof(time_str));
64 fprintf(fp, "%s WARN (%d:%s:%ld) ", time_str, getpid(), file, line);
65 break;
66 case ZC_ERROR:
67 if (error_log == NULL) return 0;
68 fp = fopen(error_log, "a");
69 if (!fp) return -1;
70 zc_time(time_str, sizeof(time_str));
71 fprintf(fp, "%s ERROR (%d:%s:%ld) ", time_str, getpid(), file, line);
72 break;
73 }
74
75 /* writing file twice(time & msg) is not atomic
76 * may cause cross
77 * but avoid log size limit */
78 va_start(args, fmt);
79 vfprintf(fp, fmt, args);
80 va_end(args);
81 fprintf(fp, "\n");
82
83 fclose(fp);
84 return 0;
85 }
86
87