Error Logging System
C
Hard
2 views
Problem Description
Maintain a global error log. Log each error to a file with a timestamp. Combine printf(sderror) and file writing.
Official Solution
#include <stdio.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
/* Global error log file */
static FILE *g_error_log = NULL;
/* Initialize error log */
int init_error_log(const char *log_path)
{
g_error_log = fopen(log_path, "a");
if (!g_error_log) {
perror("Failed to open error log");
return -1;
}
return 0;
}
/* Close error log */
void close_error_log(void)
{
if (g_error_log) {
fclose(g_error_log);
g_error_log = NULL;
}
}
/* Get formatted timestamp */
void get_timestamp(char *buffer, size_t size)
{
time_t now = time(NULL);
struct tm *tm_info = localtime(&now);
strftime(buffer, size, "%Y-%m-%d %H:%M:%S", tm_info);
}
/* Centralized error logger */
void log_error(const char *context)
{
char timestamp[32];
get_timestamp(timestamp, sizeof(timestamp));
/* Print to stderr */
fprintf(stderr,
"[%s] ERROR in %s | errno=%d (%s)n",
timestamp,
context,
errno,
strerror(errno));
/* Write to log file */
if (g_error_log) {
fprintf(g_error_log,
"[%s] ERROR in %s | errno=%d (%s)n",
timestamp,
context,
errno,
strerror(errno));
fflush(g_error_log);
}
}
/* Example function that triggers failures */
void demo_failures(void)
{
int fd;
fd = open("nonexistent.txt", O_RDONLY);
if (fd == -1) {
log_error("open(nonexistent.txt)");
}
if (write(-1, "test", 4) == -1) {
log_error("write(invalid_fd)");
}
}
int main(void)
{
if (init_error_log("error.log") != 0) {
return 1;
}
demo_failures();
close_error_log();
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!