16
16
#include < stdarg.h>
17
17
#include < stdlib.h>
18
18
#include < unistd.h>
19
-
19
+ # include < string.h >
20
20
21
21
static const char *level_strings[] = {" TRACE" , " DEBUG" , " INFO" , " WARN" , " ERROR" , " FATAL" };
22
22
@@ -54,31 +54,69 @@ static void __attribute__((constructor(102))) alaska_logger_init(void) {
54
54
55
55
56
56
57
+ #define BUFFER_SIZE 1024
58
+
59
+ static int log_vemitf (const char *format, va_list args) {
60
+ char buffer[BUFFER_SIZE];
61
+ int printed_length;
62
+ // Format the string into the buffer using snprintf
63
+ printed_length = vsnprintf (buffer, BUFFER_SIZE, format, args);
64
+
65
+ // Clean up variadic arguments
66
+ va_end (args);
67
+
68
+ // Check for truncation
69
+ if (printed_length < 0 || printed_length >= BUFFER_SIZE) {
70
+ // Handle buffer overflow or other snprintf errors if needed
71
+ return -1 ;
72
+ }
73
+
74
+ // Write the formatted string to stdout
75
+ if (write (STDOUT_FILENO, buffer, printed_length) != printed_length) {
76
+ // Handle write error
77
+ return -1 ;
78
+ }
79
+
80
+ return printed_length; // Return the number of characters written
81
+ }
82
+
83
+ static int log_emitf (const char *format, ...) {
84
+ va_list args;
85
+
86
+ // Initialize variadic arguments
87
+ va_start (args, format);
88
+
89
+ return log_vemitf (format, args);
90
+ }
91
+
92
+
93
+
57
94
58
95
namespace alaska {
59
96
void log (int level, const char *file, int line, const char *fmt, ...) {
60
97
if (level >= log_level) {
61
98
va_list args;
62
99
va_start (args, fmt);
63
100
101
+
64
102
// Grab the lock
65
103
pthread_mutex_lock (&log_mutex);
66
104
67
-
68
105
time_t t = time (NULL );
69
106
auto time = localtime (&t);
70
107
71
108
char buf[16 ];
72
109
buf[strftime (buf, sizeof (buf), " %H:%M:%S" , time )] = ' \0 ' ;
73
110
74
111
if (enable_colors) {
75
- fprintf (stderr, " %s %s%-5s\x1b [0m \x1b [90m%s:%d\x1b [0m | " , buf, level_colors[level],
112
+ log_emitf ( " %s %s%-5s\x1b [0m \x1b [90m%s:%d\x1b [0m | " , buf, level_colors[level],
76
113
level_strings[level], file, line);
77
114
} else {
78
- fprintf (stderr, " %s %-5s %s:%d | " , buf, level_strings[level], file, line);
115
+ log_emitf ( " %s %-5s %s:%d | " , buf, level_strings[level], file, line);
79
116
}
80
- vfprintf (stderr, fmt, args);
81
- fprintf (stderr, " \n " );
117
+
118
+ log_vemitf (fmt, args);
119
+ log_emitf (" \n " );
82
120
83
121
// release the lock
84
122
pthread_mutex_unlock (&log_mutex);
@@ -92,4 +130,12 @@ namespace alaska {
92
130
log_level = level;
93
131
}
94
132
}
95
- } // namespace alaska
133
+
134
+
135
+ int printf (const char *fmt, ...) {
136
+ va_list args;
137
+ va_start (args, fmt);
138
+ log_vemitf (fmt, args);
139
+ return 0 ;
140
+ }
141
+ } // namespace alaska
0 commit comments