GCC Code Coverage Report


Directory: ./
File: submodules/ECS/source/world_logger.c
Date: 2023-09-29 04:53:15
Exec Total Coverage
Lines: 2 56 3.6%
Branches: 1 24 4.2%

Line Branch Exec Source
1 /*
2 * Filename: source/world_logger.c
3 * Path: source
4 * Created Date: Monday, April 17th 2023, 11:32:33 pm
5 * Author: Thomas
6 *
7 * Copyright (c) 2023 Your Company
8 */
9
10 #include "world_logger.h"
11 #include <stdarg.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sys/stat.h>
15 #include <time.h>
16 #ifdef __linux__
17 #include <unistd.h>
18 #endif
19
20 FILE *file = NULL;
21
22 int world_log_init(FILE *f)
23 {
24 char buffer[26] = {0};
25 time_t now = time(NULL);
26 struct tm *t = localtime(&now);
27 char filename[40] = {0};
28
29 if (f != NULL) {
30 file = f;
31 }
32 else {
33 #ifdef __linux__
34 if (access("log", F_OK) == -1) {
35 if (mkdir("log", 0777) == -1) {
36 return -1;
37 }
38 }
39 strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", t);
40 sprintf(filename, "log/world-%s.log", buffer);
41 file = fopen(filename, "a");
42 if (file == NULL)
43 return -1;
44 #else
45 return -1;
46 #endif
47 }
48 return 0;
49 }
50
51 static int print_log_time(void)
52 {
53 char buffer[26] = {0};
54 time_t now = time(NULL);
55 struct tm *t = localtime(&now);
56
57 strftime(buffer, 26, "%Y-%m-%d %H:%M:%S\t", t);
58 fprintf(file, "%s", buffer);
59 fflush(file);
60 return 0;
61 }
62
63 static int print_log_level(enum world_log_level level)
64 {
65 switch (level) {
66 case WORLD_LOG_LEVEL_DEBUG:
67 fprintf(file, "DEBUG\t");
68 break;
69 case WORLD_LOG_LEVEL_INFO:
70 fprintf(file, "INFO\t");
71 break;
72 case WORLD_LOG_LEVEL_WARN:
73 fprintf(file, "WARN\t");
74 break;
75 case WORLD_LOG_LEVEL_ERROR:
76 fprintf(file, "ERROR\t");
77 break;
78 case WORLD_LOG_LEVEL_FATAL:
79 fprintf(file, "FATAL\t");
80 break;
81 default:
82 fprintf(file, "UNKNOWN\t");
83 break;
84 }
85 fflush(file);
86 return 0;
87 }
88
89 12 int world_log(enum world_log_level level, const char *filename, int line, const char *fmt, ...)
90 {
91 va_list args;
92 char *buf = NULL;
93
94
1/4
✗ Branch 0 not taken.
✓ Branch 1 taken 12 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
12 if (file == NULL || filename == NULL || fmt == NULL)
95 return -1;
96 print_log_time();
97 print_log_level(level);
98 #ifdef __linux__
99 buf = getcwd(NULL, 0);
100 #endif
101 if (buf != NULL) {
102 buf = strstr(filename, buf);
103 if (buf != NULL)
104 fprintf(file, "{cwd}%s:%d\t", buf + strlen(buf), line);
105 else
106 fprintf(file, "%s:%d\t", filename, line);
107 }
108 else {
109 fprintf(file, "%s:%d\t", filename, line);
110 }
111 va_start(args, fmt);
112 vfprintf(file, fmt, args);
113 fprintf(file, "\n");
114 va_end(args);
115 fflush(file);
116 return 0;
117 }
118
119 void world_log_destroy(void)
120 {
121 if (file)
122 fclose(file);
123 }
124