logger.c (1734B)
1 /* See LICENSE file for copyright and license details. */ 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 #include <strings.h> 6 #define SYSLOG_NAMES 7 #include <syslog.h> 8 #include <unistd.h> 9 10 #include "util.h" 11 12 static int 13 decodetable(CODE *table, char *name) 14 { 15 CODE *c; 16 17 for (c = table; c->c_name; c++) 18 if (!strcasecmp(name, c->c_name)) 19 return c->c_val; 20 eprintf("invalid priority name: %s\n", name); 21 /* NOTREACHED */ 22 return -1; 23 } 24 25 static int 26 decodepri(char *pri) 27 { 28 char *lev, *fac = pri; 29 30 if (!(lev = strchr(pri, '.'))) 31 eprintf("invalid priority name: %s\n", pri); 32 *lev++ = '\0'; 33 if (!*lev) 34 eprintf("invalid priority name: %s\n", pri); 35 return (decodetable(facilitynames, fac) & LOG_FACMASK) | 36 (decodetable(prioritynames, lev) & LOG_PRIMASK); 37 } 38 39 static void 40 usage(void) 41 { 42 eprintf("usage: %s [-is] [-p priority] [-t tag] [message ...]\n", argv0); 43 } 44 45 int 46 main(int argc, char *argv[]) 47 { 48 char *buf = NULL, *tag = NULL; 49 size_t sz = 0; 50 int logflags = 0, priority = LOG_NOTICE; 51 int i; 52 53 ARGBEGIN { 54 case 'i': 55 logflags |= LOG_PID; 56 break; 57 case 'p': 58 priority = decodepri(EARGF(usage())); 59 break; 60 case 's': 61 logflags |= LOG_PERROR; 62 break; 63 case 't': 64 tag = EARGF(usage()); 65 break; 66 default: 67 usage(); 68 } ARGEND; 69 70 openlog(tag ? tag : getlogin(), logflags, 0); 71 72 if (argc == 0) { 73 while(getline(&buf, &sz, stdin) != -1) 74 syslog(priority, "%s", buf); 75 if (ferror(stdin)) 76 eprintf("%s: read error:", "<stdin>"); 77 } else { 78 for (i = 0; i < argc; i++) 79 sz += strlen(argv[i]); 80 sz += argc; 81 buf = ecalloc(1, sz); 82 for (i = 0; i < argc; i++) { 83 strlcat(buf, argv[i], sz); 84 if (i + 1 < argc) 85 strlcat(buf, " ", sz); 86 } 87 syslog(priority, "%s", buf); 88 } 89 closelog(); 90 return 0; 91 }