error.c revision 6081
1#include <stdio.h> 2#include <string.h> 3#include <stdarg.h> 4#include <time.h> 5#include "error.h" 6 7static FILE *error_fp = NULL; 8static char *prog = NULL; 9 10 11/* 12 * Log errors to the given file. 13 */ 14void 15err_set_log(char *log_file) 16 { 17 FILE *fp; 18 19 if ((fp = fopen(log_file, "a")) == NULL) 20 err("cannot log to '%s'", log_file); 21 else 22 error_fp = fp; 23 } 24 25 26/* 27 * Set the error prefix if not logging to a file. 28 */ 29void 30err_prog_name(char *name) 31 { 32 if ((prog = strrchr(name, '/')) == NULL) 33 prog = name; 34 else 35 prog++; 36 } 37 38 39/* 40 * Log an error. 41 */ 42void 43err(char *fmt, ...) 44 { 45 va_list ap; 46 time_t now; 47 struct tm *tm; 48 FILE *fp; 49 50 if ((fp = error_fp) == NULL) 51 { 52 fp = stderr; 53 if (prog != NULL) 54 fprintf(fp, "%s: ", prog); 55 } 56 else 57 { 58 time(&now); 59 tm = localtime(&now); 60 fprintf(fp, "%04d-%02d-%02d %02d:%02d ", tm->tm_year+1900, 61 tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min); 62 } 63 64 va_start(ap, fmt); 65 vfprintf(fp, fmt, ap); 66 va_end(ap); 67 68 fprintf(fp, "\n"); 69 fflush(fp); 70 } 71