chiark / gitweb /
*** empty log message ***
[sympathy.git] / src / log.c
1 /*
2  * log.c:
3  *
4  * Copyright (c) 2008 James McKenzie <james@fishsoup.dhs.org>,
5  * All rights reserved.
6  *
7  */
8
9 static char rcsid[] = "$Id$";
10
11 /*
12  * $Log$
13  * Revision 1.2  2008/02/22 14:51:54  james
14  * *** empty log message ***
15  *
16  * Revision 1.1  2008/02/14 12:14:50  james
17  * *** empty log message ***
18  *
19  */
20
21 #include "project.h"
22
23 typedef struct
24 {
25   LOG_SIGNATURE;
26   int do_close;
27   FILE *fp;
28 } File_Log;
29
30 static void
31 flog_log (Log * _l, char *buf)
32 {
33   File_Log *l = (File_Log *) _l;
34   struct timeval tv = { 0 };
35   struct tm *tm;
36   time_t t;
37   static const char *days[] = { "Sun", "Mon", "Tue",
38     "Wed", "Thu", "Fri", "Sat"
39   };
40   static const char *months[] = {
41     "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
42     "Nov", "Dec"
43   };
44
45   if (!l->fp)
46     return;
47
48   gettimeofday (&tv, NULL);
49   t = tv.tv_sec;
50   tm = localtime (&t);
51
52   fprintf (l->fp, "%s %2d %02d:%02d:%02d.%06d ", months[tm->tm_mon],
53            tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec);
54
55   fputs (buf, l->fp);
56   fputc ('\n', l->fp);
57   fflush (l->fp);
58 }
59
60
61
62
63 static void
64 flog_close (Log * _l)
65 {
66   File_Log *l = (File_Log *) _l;
67   if (l->fp && l->do_close)
68     fclose (l->fp);
69   free (l);
70 }
71
72 Log *
73 file_log_new (char *fn)
74 {
75   File_Log *l;
76   FILE *f;
77   int dc=1;
78
79   if (fn && strcmp(fn,"-")) {
80   f = fopen (fn, "a+");
81   if (!f)
82     return NULL;
83   } else {
84         f=stderr;
85         dc=0;
86   }
87
88   l = malloc (sizeof (File_Log));
89
90   l->log = flog_log;
91   l->close = flog_close;
92   l->fp = f;
93   l->do_close=dc;
94
95   return (Log *) l;
96 }
97 void 
98 log_f (Log *log,char *fmt, ...)
99 {
100
101   int n;
102   static char *buf;
103   va_list ap;
104   static int size;
105
106   if (!log) return;
107
108   if (!size) {
109   size = 128;
110   buf = malloc (size);
111   }
112
113   if (!buf)
114     return;
115
116   while (1)
117     {
118       va_start (ap, fmt);
119       n = vsnprintf (buf , size, fmt, ap);
120       va_end (ap);
121
122       if (n > -1 && n < size) {
123         log->log(log,buf);
124         return; 
125       }
126
127       if (n > -1)               /* glibc 2.1 */
128         size = n + 1;
129       else                      /* glibc 2.0 */
130         size *= 2;              /* twice the old size */
131
132       buf = realloc (buf, size);
133
134       if (!buf)
135         return;
136     }
137 }