toybox/toys/posix/logger.c
<<
>>
Prefs
   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 * Deviations from posix: specified manner and format, defined implementation.
   8
   9USE_LOGGER(NEWTOY(logger, "t:p:s", TOYFLAG_USR|TOYFLAG_BIN))
  10
  11config LOGGER
  12  bool "logger"
  13  default y
  14  help
  15    usage: logger [-s] [-t TAG] [-p [FACILITY.]PRIORITY] [MESSAGE...]
  16
  17    Log message (or stdin) to syslog.
  18
  19    -s  Also write message to stderr
  20    -t  Use TAG instead of username to identify message source
  21    -p  Specify PRIORITY with optional FACILITY. Default is "user.notice"
  22*/
  23
  24#define FOR_logger
  25#include "toys.h"
  26
  27GLOBALS(
  28  char *p, *t;
  29)
  30
  31// find str in names[], accepting unambiguous short matches
  32// returns offset into array of match, or -1 if no match
  33int arrayfind(char *str, char *names[], int len)
  34{
  35  int j, i, ll = 0, maybe = -1;
  36
  37  for (j = 0; j<len; j++) for (i=0; ; i++) {
  38    if (!str[i]) {
  39      if (!names[j][i]) return j;
  40      if (i>ll) maybe = j;
  41      else if (i==ll) maybe = -1;
  42      break;
  43    }
  44    if (!names[j][i] || toupper(str[i])!=toupper(names[j][i])) break;
  45  }
  46
  47  return maybe;
  48}
  49
  50void logger_main(void)
  51{
  52  int facility = LOG_USER, priority = LOG_NOTICE, len = 0;
  53  char *s1, *s2, **arg,
  54    *priorities[] = {"emerg", "alert", "crit", "error", "warning", "notice",
  55                     "info", "debug"},
  56    *facilities[] = {"kern", "user", "mail", "daemon", "auth", "syslog",
  57                     "lpr", "news", "uucp", "cron", "authpriv", "ftp"};
  58
  59  if (!TT.t) TT.t = xgetpwuid(geteuid())->pw_name;
  60  if (TT.p) {
  61    if (!(s1 = strchr(TT.p, '.'))) s1 = TT.p;
  62    else {
  63      *s1++ = 0;
  64      facility = arrayfind(TT.p, facilities, ARRAY_LEN(facilities));
  65      if (facility<0) {
  66        if (sscanf(TT.p, "local%d", &facility)>0 && !(facility&~7))
  67          facility += 16;
  68        else error_exit("bad facility: %s", TT.p);
  69      }
  70      facility *= 8;
  71    }
  72
  73    priority = arrayfind(s1, priorities, ARRAY_LEN(priorities));
  74    if (priority<0) error_exit("bad priority: %s", s1);
  75  }
  76
  77  if (toys.optc) {
  78    for (arg = toys.optargs; *arg; arg++) len += strlen(*arg)+1;
  79    s1 = s2 = xmalloc(len);
  80    for (arg = toys.optargs; *arg; arg++) {
  81      if (arg != toys.optargs) *s2++ = ' ';
  82      s2 = stpcpy(s2, *arg);
  83    }
  84  } else toybuf[readall(0, s1 = toybuf, sizeof(toybuf)-1)] = 0;
  85
  86  openlog(TT.t, LOG_PERROR*FLAG(s), facility);
  87  syslog(priority, "%s", s1);
  88  closelog();
  89}
  90