xref: /unit/src/nxt_log.c (revision 1:fdc027c56872)
1 
2 /*
3  * Copyright (C) Igor Sysoev
4  * Copyright (C) NGINX, Inc.
5  */
6 
7 #include <nxt_main.h>
8 
9 
10 nxt_uint_t  nxt_debug;
11 nxt_uint_t  nxt_trace;
12 
13 
14 nxt_log_t   nxt_main_log = {
15     NXT_LOG_INFO,
16     0,
17     nxt_log_handler,
18     NULL,
19     NULL
20 };
21 
22 
23 nxt_str_t  nxt_log_levels[8] = {
24     nxt_string("emerg"),
25     nxt_string("alert"),
26     nxt_string("crit"),
27     nxt_string("error"),
28     nxt_string("warn"),
29     nxt_string("notice"),
30     nxt_string("info"),
31     nxt_string("debug")
32 };
33 
34 
35 static const u_char  *nxt_log_prefix;
36 
37 
38 void
39 nxt_log_start(const char *prefix)
40 {
41     if (prefix != NULL && *prefix != '\0') {
42         nxt_log_prefix = (u_char *) prefix;
43     }
44 }
45 
46 
47 /* STUB */
48 nxt_log_t *
49 nxt_log_set_ctx(nxt_log_t *log, nxt_log_ctx_handler_t handler, void *ctx)
50 {
51     nxt_log_t     *old;
52     nxt_thread_t  *thr;
53 
54     thr = nxt_thread();
55     old = thr->log;
56 
57     log->level = old->level;
58     log->handler = old->handler;
59     log->ctx_handler = handler;
60     log->ctx = ctx;
61 
62     thr->log = log;
63 
64     return old;
65 }
66 
67 
68 void nxt_cdecl
69 nxt_log_handler(nxt_uint_t level, nxt_log_t *log, const char *fmt, ...)
70 {
71     u_char   *p, *syslogmsg, *end;
72     va_list  args;
73     u_char   msg[NXT_MAX_ERROR_STR];
74 
75     p = msg;
76     end = msg + NXT_MAX_ERROR_STR;
77 
78     if (nxt_log_prefix != NULL) {
79         p = nxt_cpystrn(p, nxt_log_prefix, end - p);
80         *p++ = ':';
81         *p++ = ' ';
82     }
83 
84     syslogmsg = p;
85 
86     p = nxt_sprintf(p, end, (log->ident != 0) ? "[%V] *%D " : "[%V] ",
87                     &nxt_log_levels[level], log->ident);
88 
89     va_start(args, fmt);
90     p = nxt_vsprintf(p, end, fmt, args);
91     va_end(args);
92 
93     if (level != NXT_LOG_DEBUG && log->ctx_handler != NULL) {
94         p = log->ctx_handler(log->ctx, p, end);
95     }
96 
97     if (p > end - NXT_LINEFEED_SIZE) {
98         p = end - NXT_LINEFEED_SIZE;
99     }
100 
101     nxt_linefeed(p);
102 
103     (void) nxt_write_console(nxt_stderr, msg, p - msg);
104 
105     if (level <= NXT_LOG_ALERT) {
106         *(p - NXT_LINEFEED_SIZE) = '\0';
107 
108         /*
109          * Syslog LOG_ALERT level is enough, because
110          * LOG_EMERG level broadcast a message to all users.
111          */
112         nxt_write_syslog(LOG_ALERT, syslogmsg);
113     }
114 }
115