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