Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / usr.sbin / ctm / ctm_rmail / error.c
1 /*
2  * Routines for logging error messages or other informative messages.
3  *
4  * Log messages can easily contain the program name, a time stamp, system
5  * error messages, and arbitrary printf-style strings, and can be directed
6  * to stderr or a log file.
7  *
8  * Author: Stephen McKay
9  *
10  * NOTICE: This is free software.  I hope you get some use from this program.
11  * In return you should think about all the nice people who give away software.
12  * Maybe you should write some free software too.
13  *
14  * $FreeBSD: src/usr.sbin/ctm/ctm_rmail/error.c,v 1.2.12.1 2001/07/05 07:47:00 kris Exp $
15  * $DragonFly: src/usr.sbin/ctm/ctm_rmail/Attic/error.c,v 1.2 2003/06/17 04:29:53 dillon Exp $
16  */
17
18 #include <stdio.h>
19 #include <string.h>
20 #include <stdarg.h>
21 #include <time.h>
22 #include <errno.h>
23 #include "error.h"
24
25 static FILE *error_fp = NULL;
26 static char *prog = NULL;
27
28
29 /*
30  * Log errors to the given file.
31  */
32 void
33 err_set_log(char *log_file)
34     {
35     FILE *fp;
36
37     if ((fp = fopen(log_file, "a")) == NULL)
38         err("cannot log to '%s'", log_file);
39     else
40         error_fp = fp;
41     }
42
43
44 /*
45  * Set the error prefix if not logging to a file.
46  */
47 void
48 err_prog_name(char *name)
49     {
50     if ((prog = strrchr(name, '/')) == NULL)
51         prog = name;
52     else
53         prog++;
54     }
55
56
57 /*
58  * Log an error.
59  *
60  * A leading '*' in the message format means we want the system errno
61  * decoded and appended.
62  */
63 void
64 err(const char *fmt, ...)
65     {
66     va_list ap;
67     time_t now;
68     struct tm *tm;
69     FILE *fp;
70     int x = errno;
71     int want_errno;
72
73     if ((fp = error_fp) == NULL)
74         {
75         fp = stderr;
76         if (prog != NULL)
77             fprintf(fp, "%s: ", prog);
78         }
79     else
80         {
81         time(&now);
82         tm = localtime(&now);
83         fprintf(fp, "%04d-%02d-%02d %02d:%02d ", tm->tm_year+1900,
84             tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min);
85         }
86
87     want_errno = 0;
88     if (*fmt == '*')
89         want_errno++, fmt++;
90
91     va_start(ap, fmt);
92     vfprintf(fp, fmt, ap);
93     va_end(ap);
94
95     if (want_errno)
96         fprintf(fp, ": %s", strerror(x));
97
98     fprintf(fp, "\n");
99     fflush(fp);
100     }