logger.c (2195B)
1 /* see LICENSE file for copyright and license details */ 2 3 #if FEATURE_LOGGER_SYSLOG 4 #ifndef _DEFAULT_SOURCE 5 #define _DEFAULT_SOURCE 6 #endif 7 #endif 8 #include <stdio.h> 9 #include <stdlib.h> 10 #include <string.h> 11 #include <strings.h> 12 #define SYSLOG_NAMES 13 #include <syslog.h> 14 #include <unistd.h> 15 16 #include "util.h" 17 18 static int 19 decodetable(CODE *table, char *name) 20 { 21 CODE *c; 22 23 for (c = table; c->c_name; c++) 24 if (!strcasecmp(name, c->c_name)) 25 return c->c_val; 26 eprintf("invalid priority name: %s\n", name); 27 28 return -1; /* not reached */ 29 } 30 31 static int 32 decodepri(char *pri) 33 { 34 char *lev, *fac = pri; 35 36 if (!(lev = strchr(pri, '.'))) 37 eprintf("invalid priority name: %s\n", pri); 38 *lev++ = '\0'; 39 if (!*lev) 40 eprintf("invalid priority name: %s\n", pri); 41 42 return (decodetable(facilitynames, fac) & LOG_FACMASK) 43 | (decodetable(prioritynames, lev) & LOG_PRIMASK); 44 } 45 46 static void 47 usage(void) 48 { 49 eprintf("usage: %s [-is] [-p priority] [-t tag] [message ...]\n", argv0); 50 } 51 52 // ?man logger: log messages 53 // ?man arguments: message ... 54 // ?man add messages to the system log 55 int 56 main(int argc, char *argv[]) 57 { 58 size_t sz; 59 int logflags = 0, priority = LOG_NOTICE, i; 60 char *buf = NULL, *tag = NULL; 61 62 ARGBEGIN 63 { 64 // ?man -i: interactive mode or prompt for confirmation 65 case 'i': 66 logflags |= LOG_PID; 67 break; 68 // ?man -p:str: preserve file attributes 69 case 'p': 70 priority = decodepri(EARGF(usage())); 71 break; 72 // ?man -s: silent mode or print summary 73 case 's': 74 logflags |= LOG_PERROR; 75 break; 76 // ?man -t:str: sort or specify timestamp 77 case 't': 78 tag = EARGF(usage()); 79 break; 80 default: 81 usage(); 82 } 83 ARGEND 84 85 openlog(tag ? tag : getlogin(), logflags, 0); 86 87 if (!argc) { 88 while (getline(&buf, &sz, stdin) > 0) 89 syslog(priority, "%s", buf); 90 } else { 91 for (i = 0, sz = 0; i < argc; i++) 92 sz += strlen(argv[i]); 93 sz += argc; 94 buf = ecalloc(1, sz); 95 for (i = 0; i < argc; i++) { 96 estrlcat(buf, argv[i], sz); 97 if (i + 1 < argc) 98 estrlcat(buf, " ", sz); 99 } 100 syslog(priority, "%s", buf); 101 } 102 103 closelog(); 104 105 return fshut(stdin, "<stdin>"); 106 }