00001 /* 00002 Logging utility 00003 AUP2, Sec. 1.04.2 (not in book) 00004 00005 Copyright 2003 by Marc J. Rochkind. All rights reserved. 00006 May be copied only for purposes and under conditions described 00007 on the Web page www.basepath.com/aup/copyright.htm. 00008 00009 The Example Files are provided "as is," without any warranty; 00010 without even the implied warranty of merchantability or fitness 00011 for a particular purpose. The author and his publisher are not 00012 responsible for any damages, direct or incidental, resulting 00013 from the use or non-use of these Example Files. 00014 00015 The Example Files may contain defects, and some contain deliberate 00016 coding mistakes that were included for educational reasons. 00017 You are responsible for determining if and how the Example Files 00018 are to be used. 00019 00020 */ 00021 #include "defs.h" 00022 #include "logf.h" 00023 00024 static FILE *logfile = NULL; 00025 static const char *logpath = "/tmp/auplog.tmp"; 00026 static bool enable_logging = false; 00027 00028 static void init(void) 00029 { 00030 if (logfile == NULL && (logfile = fopen(logpath, "a")) != NULL) { 00031 fcntl(fileno(logfile), F_SETFD, FD_CLOEXEC); 00032 setbuf(logfile, NULL); 00033 fputc('\n', logfile); 00034 logfmt("Log file %s opened", logpath); 00035 } 00036 if (logfile == NULL) { 00037 fprintf(stderr, "Can't open logfile \"%s\"\n", logpath); 00038 exit(EXIT_FAILURE); 00039 } 00040 } 00041 00042 void logfmt(const char *format, ...) 00043 { 00044 va_list ap; 00045 char timebuf[30]; 00046 time_t tm; 00047 00048 if (enable_logging) { 00049 init(); 00050 va_start(ap, format); 00051 tm = time(NULL); 00052 strftime(timebuf, sizeof(timebuf), "%Y-%b-%d %X", localtime(&tm)); 00053 fprintf(logfile, "%s [%d]: ", timebuf, (int)getpid()); 00054 vfprintf(logfile, format, ap); 00055 fputc('\n', logfile); 00056 va_end(ap); 00057 } 00058 } 00059 00060 void logfmt_setpath(const char *path) 00061 { 00062 logpath = path; 00063 init(); 00064 } 00065 00066 void logfmt_args(int argc, char *argv[]) 00067 { 00068 int i; 00069 00070 for (i = 1; i < argc; i++) 00071 if (strcmp(argv[i], "-l") == 0) { 00072 enable_logging = true; 00073 break; 00074 } 00075 } 00076 00077 void logfmt_enable(bool enable) 00078 { 00079 enable_logging = enable; 00080 }