• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* logger.c - Log messages.
2  *
3  * Copyright 2013 Ilya Kuzmich <ilya.kuzmich@gmail.com>
4  *
5  * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/logger.html
6 
7 USE_LOGGER(NEWTOY(logger, "st:p:", TOYFLAG_USR|TOYFLAG_BIN))
8 
9 config LOGGER
10   bool "logger"
11   depends on SYSLOGD
12   default n
13   help
14     usage: logger [-s] [-t tag] [-p [facility.]priority] [message]
15 
16     Log message (or stdin) to syslog.
17 */
18 
19 #define FOR_logger
20 #include "toys.h"
21 
22 GLOBALS(
23   char *priority_arg;
24   char *ident;
25 )
26 
27 extern int logger_lookup(int where, char *key);
28 
logger_main(void)29 void logger_main(void)
30 {
31   int facility = LOG_USER, priority = LOG_NOTICE;
32   char *message = NULL;
33 
34   if (toys.optflags & FLAG_p) {
35     char *sep = strchr(TT.priority_arg, '.');
36 
37     if (sep) {
38       *sep = '\0';
39       if ((facility = logger_lookup(0, TT.priority_arg)) == -1)
40         error_exit("bad facility: %s", TT.priority_arg);
41       TT.priority_arg = sep+1;
42     }
43 
44     if ((priority = logger_lookup(1, TT.priority_arg)) == -1)
45       error_exit("bad priority: %s", TT.priority_arg);
46   }
47 
48   if (!(toys.optflags & FLAG_t)) {
49     struct passwd *pw = getpwuid(geteuid());
50 
51     if (!pw) perror_exit("getpwuid");
52     TT.ident = xstrdup(pw->pw_name);
53   }
54 
55   if (toys.optc) {
56     int length = 0, pos = 0;
57 
58     for (;*toys.optargs; toys.optargs++) {
59       length += strlen(*(toys.optargs)) + 1; // plus one for the args spacing
60       message = xrealloc(message, length + 1); // another one for the null byte
61 
62       sprintf(message + pos, "%s ", *toys.optargs);
63       pos = length;
64     }
65   } else {
66     toybuf[readall(0, toybuf, 4096-1)] = '\0';
67     message = toybuf;
68   }
69 
70   openlog(TT.ident, (toys.optflags & FLAG_s ? LOG_PERROR : 0) , facility);
71   syslog(priority, "%s", message);
72   closelog();
73 }
74