logger.c 2.5 KB

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