/* * log.c: * * Copyright (c) 2008 James McKenzie , * All rights reserved. * */ static char rcsid[] = "$Id$"; /* * $Log$ * Revision 1.10 2008/03/07 12:37:04 james * *** empty log message *** * * Revision 1.9 2008/03/03 06:20:14 james * *** empty log message *** * * Revision 1.8 2008/03/03 06:04:42 james * *** empty log message *** * * Revision 1.7 2008/03/03 06:04:18 james * *** empty log message *** * * Revision 1.6 2008/03/02 10:37:56 james * *** empty log message *** * * Revision 1.5 2008/02/27 01:31:14 james * *** empty log message *** * * Revision 1.4 2008/02/27 00:54:16 james * *** empty log message *** * * Revision 1.3 2008/02/23 11:48:37 james * *** empty log message *** * * Revision 1.2 2008/02/22 14:51:54 james * *** empty log message *** * * Revision 1.1 2008/02/14 12:14:50 james * *** empty log message *** * */ #include "project.h" typedef struct { LOG_SIGNATURE; int do_close; int rotate; FILE *fp; char *filename; } File_Log; static void flog_log (Log * _l, char *buf) { File_Log *l = (File_Log *) _l; struct timeval tv = { 0 }; struct tm *tm; time_t t; static const char *days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static const char *months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; if (!l->fp) return; gettimeofday (&tv, NULL); t = tv.tv_sec; tm = localtime (&t); fprintf (l->fp, "%s %2d %02d:%02d:%02d.%06d ", months[tm->tm_mon], tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec); fputs (buf, l->fp); fputc ('\n', l->fp); fflush (l->fp); if (l->rotate && rotate_check (l->filename)) { fclose (l->fp); rotate (l->filename); l->fp = fopen (l->filename, "a+"); } } static void flog_close (Log * _l) { File_Log *l = (File_Log *) _l; if (l->fp && l->do_close) fclose (l->fp); if (l->filename) free (l->filename); free (l); } Log * file_log_new (char *fn, int rotate) { File_Log *l; FILE *f; int dc = 1; if (fn && strcmp (fn, "-")) { f = fopen (fn, "a+"); if (!f) return NULL; } else { f = stderr; dc = 0; } l = malloc (sizeof (File_Log)); l->log = flog_log; l->close = flog_close; l->fp = f; l->do_close = dc; l->rotate = rotate; l->filename = strdup (fn); fput_cp (f, 0xffef); return (Log *) l; } void log_f (Log * log, char *fmt, ...) { int n; static char *buf; va_list ap; static int size; if (!log) return; if (!size) { size = 128; buf = malloc (size); } if (!buf) return; while (1) { va_start (ap, fmt); n = vsnprintf (buf, size, fmt, ap); va_end (ap); if (n > -1 && n < size) { log->log (log, buf); return; } if (n > -1) /* glibc 2.1 */ size = n + 1; else /* glibc 2.0 */ size *= 2; /* twice the old size */ buf = realloc (buf, size); if (!buf) return; } }