nmdb: Add an option to save the pidfile
[nmdb.git] / nmdb / log.c
blob302635021e5436cc9e44ff24be65f99af1997797
2 #include <stdio.h> /* vsprintf() */
3 #include <stdarg.h>
4 #include <sys/types.h> /* open() */
5 #include <sys/stat.h>
6 #include <fcntl.h>
7 #include <unistd.h> /* write() */
8 #include <string.h> /* strcmp(), strerror() */
9 #include <errno.h> /* errno */
10 #include <time.h> /* time() and friends */
12 #include "log.h"
13 #include "common.h"
16 /* Logging file descriptor, -1 if logging is disabled */
17 static int logfd = -1;
20 int log_init(void)
22 if (settings.logfname == NULL) {
23 logfd = -1;
24 return 1;
27 if (strcmp(settings.logfname, "-") == 0) {
28 logfd = 1;
29 return 1;
32 logfd = open(settings.logfname, O_WRONLY | O_APPEND | O_CREAT, 0660);
33 if (logfd < 0)
34 return 0;
36 return 1;
39 int log_reopen(void)
41 /* Just call log_init(), it will do just fine as we don't need any
42 * special considerations for reopens */
43 return log_init();
46 void wlog(const char *fmt, ...)
48 int r, tr;
49 va_list ap;
50 char str[MAX_LOG_STR];
51 char timestr[MAX_LOG_STR];
52 time_t t;
53 struct tm *tmp;
55 if (logfd == -1)
56 return;
58 t = time(NULL);
59 tmp = localtime(&t);
60 tr = strftime(timestr, MAX_LOG_STR, "%F %H:%M:%S ", tmp);
62 va_start(ap, fmt);
63 r = vsnprintf(str, MAX_LOG_STR, fmt, ap);
64 va_end(ap);
66 write(logfd, timestr, tr);
67 write(logfd, str, r);
70 void errlog(const char *s)
72 wlog("%s: %s\n", s, strerror(errno));
75 void write_pid()
77 FILE *f;
79 if (settings.pidfile == NULL)
80 return;
82 f = fopen(settings.pidfile, "w");
83 if (f == NULL) {
84 errlog("Can't open pidfile for writing");
85 return;
88 fprintf(f, "%d\n", getpid());
90 fclose(f);