Amit Pundir | d477f82 | 2020-02-07 22:26:08 +0530 | [diff] [blame] | 1 | #include <stdbool.h> |
| 2 | #include <stdio.h> |
| 3 | #include <stdarg.h> |
| 4 | #include <syslog.h> |
| 5 | |
| 6 | #define QLOG_BUF_SIZE 512 |
| 7 | |
| 8 | static const char default_tag[] = "libqrtr"; |
| 9 | static const char *current_tag = default_tag; |
| 10 | static int min_priority = LOG_INFO; |
| 11 | |
| 12 | static bool logging_to_syslog = false; |
| 13 | |
| 14 | void qlog_setup(const char *tag, bool use_syslog) |
| 15 | { |
| 16 | current_tag = tag; |
| 17 | logging_to_syslog = use_syslog; |
| 18 | |
| 19 | openlog(tag, LOG_PID, LOG_USER); |
| 20 | } |
| 21 | |
| 22 | void qlog_set_min_priority(int priority) |
| 23 | { |
| 24 | if (priority < LOG_EMERG || priority > LOG_DEBUG) |
| 25 | return; |
| 26 | |
| 27 | min_priority = priority; |
| 28 | } |
| 29 | |
| 30 | static const char *get_priority_string(int priority) |
| 31 | { |
| 32 | switch (priority) { |
| 33 | case LOG_EMERG: |
| 34 | return "EMERG"; |
| 35 | case LOG_ALERT: |
| 36 | return "ALERT"; |
| 37 | case LOG_CRIT: |
| 38 | return "CRIT"; |
| 39 | case LOG_ERR: |
| 40 | return "ERROR"; |
| 41 | case LOG_WARNING: |
| 42 | return "WARNING"; |
| 43 | case LOG_NOTICE: |
| 44 | return "NOTICE"; |
| 45 | case LOG_INFO: |
| 46 | return "INFO"; |
| 47 | case LOG_DEBUG: |
| 48 | return "DEBUG"; |
| 49 | } |
| 50 | return ""; |
| 51 | } |
| 52 | |
| 53 | void qlog(int priority, const char *format, ...) |
| 54 | { |
| 55 | va_list ap; |
| 56 | |
| 57 | if (priority > min_priority) |
| 58 | return; |
| 59 | |
| 60 | va_start(ap, format); |
| 61 | |
| 62 | if (logging_to_syslog) { |
| 63 | vsyslog(priority, format, ap); |
| 64 | } else { |
| 65 | char buf[QLOG_BUF_SIZE]; |
| 66 | vsnprintf(buf, QLOG_BUF_SIZE, format, ap); |
| 67 | |
| 68 | fprintf(stderr, "%s %s: %s\n", |
| 69 | get_priority_string(priority), current_tag, buf); |
| 70 | } |
| 71 | |
| 72 | va_end(ap); |
| 73 | } |