sbase

suckless unix tools
git clone git://git.2f30.org/sbase
Log | Files | Refs | README | LICENSE

logger.c (1692B)


      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 
     22 	return -1; /* not reached */
     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 
     36 	return (decodetable(facilitynames, fac) & LOG_FACMASK) |
     37 	       (decodetable(prioritynames, lev) & LOG_PRIMASK);
     38 }
     39 
     40 static void
     41 usage(void)
     42 {
     43 	eprintf("usage: %s [-is] [-p priority] [-t tag] [message ...]\n", argv0);
     44 }
     45 
     46 int
     47 main(int argc, char *argv[])
     48 {
     49 	size_t sz;
     50 	int logflags = 0, priority = LOG_NOTICE, i;
     51 	char *buf = NULL, *tag = NULL;
     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) {
     73 		while (getline(&buf, &sz, stdin) > 0)
     74 			syslog(priority, "%s", buf);
     75 	} else {
     76 		for (i = 0, sz = 0; i < argc; i++)
     77 			sz += strlen(argv[i]);
     78 		sz += argc;
     79 		buf = ecalloc(1, sz);
     80 		for (i = 0; i < argc; i++) {
     81 			estrlcat(buf, argv[i], sz);
     82 			if (i + 1 < argc)
     83 				estrlcat(buf, " ", sz);
     84 		}
     85 		syslog(priority, "%s", buf);
     86 	}
     87 
     88 	closelog();
     89 
     90 	return fshut(stdin, "<stdin>");
     91 }