2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Asterisk Logger
25 * \author Mark Spencer <markster@digium.com>
29 * define _ASTERISK_LOGGER_H to prevent the inclusion of logger.h;
30 * it redefines LOG_* which we need to define syslog_level_map.
31 * later, we force the inclusion of logger.h again.
33 #define _ASTERISK_LOGGER_H
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
39 * WARNING: additional #include directives should NOT be placed here, they
40 * should be placed AFTER '#undef _ASTERISK_LOGGER_H' below
42 #include "asterisk/_private.h"
43 #include "asterisk/paths.h" /* use ast_config_AST_LOG_DIR */
50 #define MAX_BACKTRACE_FRAMES 20
53 #define SYSLOG_NAMES /* so we can map syslog facilities names to their numeric values,
54 from <syslog.h> which is included by logger.h */
57 static int syslog_level_map[] = {
59 LOG_INFO, /* arbitrary equivalent of LOG_EVENT */
67 #define SYSLOG_NLEVELS sizeof(syslog_level_map) / sizeof(int)
69 #undef _ASTERISK_LOGGER_H /* now include logger.h */
70 #include "asterisk/logger.h"
71 #include "asterisk/lock.h"
72 #include "asterisk/channel.h"
73 #include "asterisk/config.h"
74 #include "asterisk/term.h"
75 #include "asterisk/cli.h"
76 #include "asterisk/utils.h"
77 #include "asterisk/manager.h"
78 #include "asterisk/threadstorage.h"
79 #include "asterisk/strings.h"
80 #include "asterisk/pbx.h"
81 #include "asterisk/app.h"
83 #if defined(__linux__) && !defined(__NR_gettid)
84 #include <asm/unistd.h>
87 #if defined(__linux__) && defined(__NR_gettid)
88 #define GETTID() syscall(__NR_gettid)
90 #define GETTID() getpid()
93 static char dateformat[256] = "%b %e %T"; /* Original Asterisk Format */
95 static char queue_log_name[256] = QUEUELOG;
96 static char exec_after_rotate[256] = "";
98 static int filesize_reload_needed;
99 static int global_logmask = -1;
101 enum rotatestrategy {
102 SEQUENTIAL = 1 << 0, /* Original method - create a new file, in order */
103 ROTATE = 1 << 1, /* Rotate all files, such that the oldest file has the highest suffix */
104 TIMESTAMP = 1 << 2, /* Append the epoch timestamp onto the end of the archived file */
105 } rotatestrategy = SEQUENTIAL;
108 unsigned int queue_log:1;
109 unsigned int event_log:1;
110 } logfiles = { 1, 1 };
112 static char hostname[MAXHOSTNAMELEN];
121 int logmask; /* What to log to this channel */
122 int disabled; /* If this channel is disabled or not */
123 int facility; /* syslog facility */
124 enum logtypes type; /* Type of log channel */
125 FILE *fileptr; /* logfile logging file pointer */
126 char filename[256]; /* Filename */
127 AST_LIST_ENTRY(logchannel) list;
130 static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
138 enum logmsgtypes type;
145 AST_LIST_ENTRY(logmsg) list;
149 static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
150 static pthread_t logthread = AST_PTHREADT_NULL;
151 static ast_cond_t logcond;
152 static int close_logger_thread;
154 static FILE *eventlog;
157 /*! \brief Logging channels used in the Asterisk logging system */
158 static char *levels[] = {
168 /*! \brief Colors used in the console for logging */
169 static int colors[] = {
179 AST_THREADSTORAGE(verbose_buf);
180 #define VERBOSE_BUF_INIT_SIZE 256
182 AST_THREADSTORAGE(log_buf);
183 #define LOG_BUF_INIT_SIZE 256
185 static int make_components(const char *s, int lineno)
189 char *stringp = ast_strdupa(s);
191 while ((w = strsep(&stringp, ","))) {
192 w = ast_skip_blanks(w);
193 if (!strcasecmp(w, "error"))
194 res |= (1 << __LOG_ERROR);
195 else if (!strcasecmp(w, "warning"))
196 res |= (1 << __LOG_WARNING);
197 else if (!strcasecmp(w, "notice"))
198 res |= (1 << __LOG_NOTICE);
199 else if (!strcasecmp(w, "event"))
200 res |= (1 << __LOG_EVENT);
201 else if (!strcasecmp(w, "debug"))
202 res |= (1 << __LOG_DEBUG);
203 else if (!strcasecmp(w, "verbose"))
204 res |= (1 << __LOG_VERBOSE);
205 else if (!strcasecmp(w, "dtmf"))
206 res |= (1 << __LOG_DTMF);
208 fprintf(stderr, "Logfile Warning: Unknown keyword '%s' at line %d of logger.conf\n", w, lineno);
215 static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno)
217 struct logchannel *chan;
223 if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan))))
226 if (!strcasecmp(channel, "console")) {
227 chan->type = LOGTYPE_CONSOLE;
228 } else if (!strncasecmp(channel, "syslog", 6)) {
231 * syslog.facility => level,level,level
233 facility = strchr(channel, '.');
234 if (!facility++ || !facility) {
240 * Walk through the list of facilitynames (defined in sys/syslog.h)
241 * to see if we can find the one we have been given
244 cptr = facilitynames;
245 while (cptr->c_name) {
246 if (!strcasecmp(facility, cptr->c_name)) {
247 chan->facility = cptr->c_val;
254 if (!strcasecmp(facility, "kern"))
255 chan->facility = LOG_KERN;
256 else if (!strcasecmp(facility, "USER"))
257 chan->facility = LOG_USER;
258 else if (!strcasecmp(facility, "MAIL"))
259 chan->facility = LOG_MAIL;
260 else if (!strcasecmp(facility, "DAEMON"))
261 chan->facility = LOG_DAEMON;
262 else if (!strcasecmp(facility, "AUTH"))
263 chan->facility = LOG_AUTH;
264 else if (!strcasecmp(facility, "SYSLOG"))
265 chan->facility = LOG_SYSLOG;
266 else if (!strcasecmp(facility, "LPR"))
267 chan->facility = LOG_LPR;
268 else if (!strcasecmp(facility, "NEWS"))
269 chan->facility = LOG_NEWS;
270 else if (!strcasecmp(facility, "UUCP"))
271 chan->facility = LOG_UUCP;
272 else if (!strcasecmp(facility, "CRON"))
273 chan->facility = LOG_CRON;
274 else if (!strcasecmp(facility, "LOCAL0"))
275 chan->facility = LOG_LOCAL0;
276 else if (!strcasecmp(facility, "LOCAL1"))
277 chan->facility = LOG_LOCAL1;
278 else if (!strcasecmp(facility, "LOCAL2"))
279 chan->facility = LOG_LOCAL2;
280 else if (!strcasecmp(facility, "LOCAL3"))
281 chan->facility = LOG_LOCAL3;
282 else if (!strcasecmp(facility, "LOCAL4"))
283 chan->facility = LOG_LOCAL4;
284 else if (!strcasecmp(facility, "LOCAL5"))
285 chan->facility = LOG_LOCAL5;
286 else if (!strcasecmp(facility, "LOCAL6"))
287 chan->facility = LOG_LOCAL6;
288 else if (!strcasecmp(facility, "LOCAL7"))
289 chan->facility = LOG_LOCAL7;
292 if (0 > chan->facility) {
293 fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
298 chan->type = LOGTYPE_SYSLOG;
299 snprintf(chan->filename, sizeof(chan->filename), "%s", channel);
300 openlog("asterisk", LOG_PID, chan->facility);
302 if (channel[0] == '/') {
303 if (!ast_strlen_zero(hostname)) {
304 snprintf(chan->filename, sizeof(chan->filename), "%s.%s", channel, hostname);
306 ast_copy_string(chan->filename, channel, sizeof(chan->filename));
310 if (!ast_strlen_zero(hostname)) {
311 snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s", ast_config_AST_LOG_DIR, channel, hostname);
313 snprintf(chan->filename, sizeof(chan->filename), "%s/%s", ast_config_AST_LOG_DIR, channel);
315 chan->fileptr = fopen(chan->filename, "a");
316 if (!chan->fileptr) {
317 /* Can't log here, since we're called with a lock */
318 fprintf(stderr, "Logger Warning: Unable to open log file '%s': %s\n", chan->filename, strerror(errno));
320 chan->type = LOGTYPE_FILE;
322 chan->logmask = make_components(components, lineno);
326 static void init_logger_chain(int locked)
328 struct logchannel *chan;
329 struct ast_config *cfg;
330 struct ast_variable *var;
332 struct ast_flags config_flags = { 0 };
334 if (!(cfg = ast_config_load2("logger.conf", "logger", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID)
337 /* delete our list of log channels */
339 AST_RWLIST_WRLOCK(&logchannels);
340 while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list)))
343 AST_RWLIST_UNLOCK(&logchannels);
350 /* If no config file, we're fine, set default options. */
353 fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
355 fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
356 if (!(chan = ast_calloc(1, sizeof(*chan))))
358 chan->type = LOGTYPE_CONSOLE;
359 chan->logmask = 28; /*warning,notice,error */
361 AST_RWLIST_WRLOCK(&logchannels);
362 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
364 AST_RWLIST_UNLOCK(&logchannels);
365 global_logmask |= chan->logmask;
369 if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
371 if (gethostname(hostname, sizeof(hostname) - 1)) {
372 ast_copy_string(hostname, "unknown", sizeof(hostname));
373 fprintf(stderr, "What box has no hostname???\n");
379 if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
380 ast_copy_string(dateformat, s, sizeof(dateformat));
382 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
383 if ((s = ast_variable_retrieve(cfg, "general", "queue_log")))
384 logfiles.queue_log = ast_true(s);
385 if ((s = ast_variable_retrieve(cfg, "general", "event_log")))
386 logfiles.event_log = ast_true(s);
387 if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name")))
388 ast_copy_string(queue_log_name, s, sizeof(queue_log_name));
389 if ((s = ast_variable_retrieve(cfg, "general", "exec_after_rotate")))
390 ast_copy_string(exec_after_rotate, s, sizeof(exec_after_rotate));
391 if ((s = ast_variable_retrieve(cfg, "general", "rotatestrategy"))) {
392 if (strcasecmp(s, "timestamp") == 0)
393 rotatestrategy = TIMESTAMP;
394 else if (strcasecmp(s, "rotate") == 0)
395 rotatestrategy = ROTATE;
396 else if (strcasecmp(s, "sequential") == 0)
397 rotatestrategy = SEQUENTIAL;
399 fprintf(stderr, "Unknown rotatestrategy: %s\n", s);
401 if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp"))) {
402 rotatestrategy = ast_true(s) ? TIMESTAMP : SEQUENTIAL;
403 fprintf(stderr, "rotatetimestamp option has been deprecated. Please use rotatestrategy instead.\n");
408 AST_RWLIST_WRLOCK(&logchannels);
409 var = ast_variable_browse(cfg, "logfiles");
410 for (; var; var = var->next) {
411 if (!(chan = make_logchannel(var->name, var->value, var->lineno)))
413 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
414 global_logmask |= chan->logmask;
417 AST_RWLIST_UNLOCK(&logchannels);
419 ast_config_destroy(cfg);
422 void ast_child_verbose(int level, const char *fmt, ...)
424 char *msg = NULL, *emsg = NULL, *sptr, *eptr;
428 /* Don't bother, if the level isn't that high */
429 if (option_verbose < level) {
435 if ((size = vsnprintf(msg, 0, fmt, ap)) < 0) {
442 if (!(msg = ast_malloc(size + 1))) {
447 vsnprintf(msg, size + 1, fmt, aq);
450 if (!(emsg = ast_malloc(size * 2 + 1))) {
455 for (sptr = msg, eptr = emsg; ; sptr++) {
466 fprintf(stdout, "verbose \"%s\" %d\n", emsg, level);
471 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
478 if (ast_check_realtime("queue_log")) {
480 vsnprintf(qlog_msg, sizeof(qlog_msg), fmt, ap);
482 snprintf(time_str, sizeof(time_str), "%ld", (long)time(NULL));
483 ast_store_realtime("queue_log", "time", time_str,
485 "queuename", queuename,
493 qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
494 vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
497 AST_RWLIST_RDLOCK(&logchannels);
499 fprintf(qlog, "%s\n", qlog_msg);
502 AST_RWLIST_UNLOCK(&logchannels);
506 static int rotate_file(const char *filename)
510 int x, y, which, found, res = 0, fd;
511 char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
513 switch (rotatestrategy) {
516 snprintf(new, sizeof(new), "%s.%d", filename, x);
517 fd = open(new, O_RDONLY);
523 if (rename(filename, new)) {
524 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
529 snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
530 if (rename(filename, new)) {
531 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
536 /* Find the next empty slot, including a possible suffix */
539 for (which = 0; which < ARRAY_LEN(suffixes); which++) {
540 snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
541 fd = open(new, O_RDONLY);
553 /* Found an empty slot */
554 for (y = x; y > 0; y--) {
555 for (which = 0; which < ARRAY_LEN(suffixes); which++) {
556 snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
557 fd = open(old, O_RDONLY);
559 /* Found the right suffix */
561 snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
562 if (rename(old, new)) {
563 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
571 /* Finally, rename the current file */
572 snprintf(new, sizeof(new), "%s.0", filename);
573 if (rename(filename, new)) {
574 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
579 if (!ast_strlen_zero(exec_after_rotate)) {
580 struct ast_channel *c = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Logger/rotate");
582 pbx_builtin_setvar_helper(c, "filename", filename);
583 pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
584 if (ast_safe_system(buf) != -1) {
585 ast_log(LOG_WARNING, "error executing '%s'\n", buf);
587 c = ast_channel_release(c);
592 static int reload_logger(int rotate)
594 char old[PATH_MAX] = "";
595 int event_rotate = rotate, queue_rotate = rotate;
596 struct logchannel *f;
600 AST_RWLIST_WRLOCK(&logchannels);
604 /* Check filesize - this one typically doesn't need an auto-rotate */
605 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
606 if (stat(old, &st) != 0 || st.st_size > 0x40000000) { /* Arbitrarily, 1 GB */
620 /* Check filesize - this one typically doesn't need an auto-rotate */
621 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
622 if (stat(old, &st) != 0 || st.st_size > 0x40000000) { /* Arbitrarily, 1 GB */
634 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
636 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
638 f->disabled = 0; /* Re-enable logging at reload */
639 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
641 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
642 fclose(f->fileptr); /* Close file */
645 rotate_file(f->filename);
649 filesize_reload_needed = 0;
651 init_logger_chain(1 /* locked */);
653 if (logfiles.event_log) {
654 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
658 eventlog = fopen(old, "a");
660 ast_log(LOG_EVENT, "Restarted Asterisk Event Logger\n");
661 ast_verb(1, "Asterisk Event Logger restarted\n");
663 ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
668 if (logfiles.queue_log) {
669 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
673 qlog = fopen(old, "a");
675 AST_RWLIST_UNLOCK(&logchannels);
676 ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
677 AST_RWLIST_WRLOCK(&logchannels);
678 ast_log(LOG_EVENT, "Restarted Asterisk Queue Logger\n");
679 ast_verb(1, "Asterisk Queue Logger restarted\n");
681 ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
686 AST_RWLIST_UNLOCK(&logchannels);
691 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
692 a full Asterisk reload) */
693 int logger_reload(void)
696 return RESULT_FAILURE;
697 return RESULT_SUCCESS;
700 static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
704 e->command = "logger reload";
706 "Usage: logger reload\n"
707 " Reloads the logger subsystem state. Use after restarting syslogd(8) if you are using syslog logging.\n";
712 if (reload_logger(0)) {
713 ast_cli(a->fd, "Failed to reload the logger\n");
719 static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
723 e->command = "logger rotate";
725 "Usage: logger rotate\n"
726 " Rotates and Reopens the log files.\n";
731 if (reload_logger(1)) {
732 ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
738 static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
746 e->command = "logger set level";
748 "Usage: logger set level\n"
749 " Set a specific log level to enabled/disabled for this console.\n";
756 return CLI_SHOWUSAGE;
758 for (x = 0; x <= NUMLOGLEVELS; x++) {
759 if (!strcasecmp(a->argv[3], levels[x])) {
765 state = ast_true(a->argv[4]) ? 1 : 0;
768 ast_console_toggle_loglevel(a->fd, level, state);
769 ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
771 return CLI_SHOWUSAGE;
776 /*! \brief CLI command to show logging system configuration */
777 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
779 #define FORMATL "%-35.35s %-8.8s %-9.9s "
780 struct logchannel *chan;
783 e->command = "logger show channels";
785 "Usage: logger show channels\n"
786 " List configured logger channels.\n";
791 ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
792 ast_cli(a->fd, "Configuration\n");
793 ast_cli(a->fd, FORMATL, "-------", "----", "------");
794 ast_cli(a->fd, "-------------\n");
795 AST_RWLIST_RDLOCK(&logchannels);
796 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
797 ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
798 chan->disabled ? "Disabled" : "Enabled");
799 ast_cli(a->fd, " - ");
800 if (chan->logmask & (1 << __LOG_DEBUG))
801 ast_cli(a->fd, "Debug ");
802 if (chan->logmask & (1 << __LOG_DTMF))
803 ast_cli(a->fd, "DTMF ");
804 if (chan->logmask & (1 << __LOG_VERBOSE))
805 ast_cli(a->fd, "Verbose ");
806 if (chan->logmask & (1 << __LOG_WARNING))
807 ast_cli(a->fd, "Warning ");
808 if (chan->logmask & (1 << __LOG_NOTICE))
809 ast_cli(a->fd, "Notice ");
810 if (chan->logmask & (1 << __LOG_ERROR))
811 ast_cli(a->fd, "Error ");
812 if (chan->logmask & (1 << __LOG_EVENT))
813 ast_cli(a->fd, "Event ");
814 ast_cli(a->fd, "\n");
816 AST_RWLIST_UNLOCK(&logchannels);
817 ast_cli(a->fd, "\n");
823 void (*verboser)(const char *string);
824 AST_LIST_ENTRY(verb) list;
827 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
829 static struct ast_cli_entry cli_logger[] = {
830 AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
831 AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
832 AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
833 AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console")
836 static int handle_SIGXFSZ(int sig)
838 /* Indicate need to reload */
839 filesize_reload_needed = 1;
843 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, char *str, long pid)
847 if (level >= SYSLOG_NLEVELS) {
848 /* we are locked here, so cannot ast_log() */
849 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
853 if (level == __LOG_VERBOSE) {
854 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: %s", pid, str);
856 } else if (level == __LOG_DTMF) {
857 snprintf(buf, sizeof(buf), "DTMF[%ld]: %s", pid, str);
860 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: %s",
861 levels[level], pid, file, line, function, str);
864 term_strip(buf, buf, strlen(buf) + 1);
865 syslog(syslog_level_map[level], "%s", buf);
868 /*! \brief Print a normal log message to the channels */
869 static void logger_print_normal(struct logmsg *logmsg)
871 struct logchannel *chan = NULL;
874 AST_RWLIST_RDLOCK(&logchannels);
876 if (logfiles.event_log && logmsg->level == __LOG_EVENT) {
877 fprintf(eventlog, "%s asterisk[%ld]: %s", logmsg->date, (long)getpid(), logmsg->str);
879 AST_RWLIST_UNLOCK(&logchannels);
883 if (!AST_RWLIST_EMPTY(&logchannels)) {
884 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
885 /* If the channel is disabled, then move on to the next one */
888 /* Check syslog channels */
889 if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
890 ast_log_vsyslog(logmsg->level, logmsg->file, logmsg->line, logmsg->function, logmsg->str, logmsg->process_id);
891 /* Console channels */
892 } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
894 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
896 /* If the level is verbose, then skip it */
897 if (logmsg->level == __LOG_VERBOSE)
900 /* Turn the numerical line number into a string */
901 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
902 /* Build string to print out */
903 snprintf(buf, sizeof(buf), "[%s] %s[%ld]: %s:%s %s: %s",
905 term_color(tmp1, levels[logmsg->level], colors[logmsg->level], 0, sizeof(tmp1)),
907 term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
908 term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
909 term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
912 ast_console_puts_mutable(buf, logmsg->level);
914 } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
917 /* If no file pointer exists, skip it */
921 /* Print out to the file */
922 res = fprintf(chan->fileptr, "[%s] %s[%ld] %s: %s",
923 logmsg->date, levels[logmsg->level], logmsg->process_id, logmsg->file, logmsg->str);
924 if (res <= 0 && !ast_strlen_zero(logmsg->str)) {
925 fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
926 if (errno == ENOMEM || errno == ENOSPC)
927 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
929 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
930 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
932 } else if (res > 0) {
933 fflush(chan->fileptr);
937 } else if (logmsg->level != __LOG_VERBOSE) {
938 fputs(logmsg->str, stdout);
941 AST_RWLIST_UNLOCK(&logchannels);
943 /* If we need to reload because of the file size, then do so */
944 if (filesize_reload_needed) {
946 ast_log(LOG_EVENT, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
947 ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
953 /*! \brief Print a verbose message to the verbosers */
954 static void logger_print_verbose(struct logmsg *logmsg)
956 struct verb *v = NULL;
958 /* Iterate through the list of verbosers and pass them the log message string */
959 AST_RWLIST_RDLOCK(&verbosers);
960 AST_RWLIST_TRAVERSE(&verbosers, v, list)
961 v->verboser(logmsg->str);
962 AST_RWLIST_UNLOCK(&verbosers);
967 /*! \brief Actual logging thread */
968 static void *logger_thread(void *data)
970 struct logmsg *next = NULL, *msg = NULL;
973 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
974 AST_LIST_LOCK(&logmsgs);
975 if (AST_LIST_EMPTY(&logmsgs)) {
976 if (close_logger_thread) {
979 ast_cond_wait(&logcond, &logmsgs.lock);
982 next = AST_LIST_FIRST(&logmsgs);
983 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
984 AST_LIST_UNLOCK(&logmsgs);
986 /* Otherwise go through and process each message in the order added */
987 while ((msg = next)) {
988 /* Get the next entry now so that we can free our current structure later */
989 next = AST_LIST_NEXT(msg, list);
991 /* Depending on the type, send it to the proper function */
992 if (msg->type == LOGMSG_NORMAL)
993 logger_print_normal(msg);
994 else if (msg->type == LOGMSG_VERBOSE)
995 logger_print_verbose(msg);
997 /* Free the data since we are done */
1001 /* If we should stop, then stop */
1002 if (close_logger_thread)
1009 int init_logger(void)
1014 /* auto rotate if sig SIGXFSZ comes a-knockin */
1015 (void) signal(SIGXFSZ, (void *) handle_SIGXFSZ);
1017 /* start logger thread */
1018 ast_cond_init(&logcond, NULL);
1019 if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
1020 ast_cond_destroy(&logcond);
1024 /* register the logger cli commands */
1025 ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
1027 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
1029 /* create log channels */
1030 init_logger_chain(0 /* locked */);
1032 /* create the eventlog */
1033 if (logfiles.event_log) {
1034 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
1035 eventlog = fopen(tmp, "a");
1037 ast_log(LOG_EVENT, "Started Asterisk Event Logger\n");
1038 ast_verb(1, "Asterisk Event Logger Started %s\n", tmp);
1040 ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
1045 if (logfiles.queue_log) {
1046 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
1047 qlog = fopen(tmp, "a");
1048 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
1053 void close_logger(void)
1055 struct logchannel *f = NULL;
1057 /* Stop logger thread */
1058 AST_LIST_LOCK(&logmsgs);
1059 close_logger_thread = 1;
1060 ast_cond_signal(&logcond);
1061 AST_LIST_UNLOCK(&logmsgs);
1063 if (logthread != AST_PTHREADT_NULL)
1064 pthread_join(logthread, NULL);
1066 AST_RWLIST_WRLOCK(&logchannels);
1078 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
1079 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
1085 closelog(); /* syslog */
1087 AST_RWLIST_UNLOCK(&logchannels);
1093 * \brief send log messages to syslog and/or the console
1095 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
1097 struct logmsg *logmsg = NULL;
1098 struct ast_str *buf = NULL;
1100 struct timeval now = ast_tvnow();
1104 if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1107 if (AST_RWLIST_EMPTY(&logchannels)) {
1109 * we don't have the logger chain configured yet,
1110 * so just log to stdout
1112 if (level != __LOG_VERBOSE) {
1115 result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1117 if (result != AST_DYNSTR_BUILD_FAILED) {
1118 term_filter_escapes(ast_str_buffer(buf));
1119 fputs(ast_str_buffer(buf), stdout);
1125 /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
1126 are non-zero; LOG_DEBUG messages can still be displayed if option_debug
1127 is zero, if option_verbose is non-zero (this allows for 'level zero'
1128 LOG_DEBUG messages to be displayed, if the logmask on any channel
1131 if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
1134 /* Ignore anything that never gets logged anywhere */
1135 if (!(global_logmask & (1 << level)))
1140 res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1143 /* If the build failed, then abort and free this structure */
1144 if (res == AST_DYNSTR_BUILD_FAILED)
1147 /* Create a new logging message */
1148 if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1151 /* Copy string over */
1152 strcpy(logmsg->str, ast_str_buffer(buf));
1154 /* Set type to be normal */
1155 logmsg->type = LOGMSG_NORMAL;
1157 /* Create our date/time */
1158 ast_localtime(&now, &tm, NULL);
1159 ast_strftime(logmsg->date, sizeof(logmsg->date), dateformat, &tm);
1161 /* Copy over data */
1162 logmsg->level = level;
1163 logmsg->line = line;
1164 ast_copy_string(logmsg->file, file, sizeof(logmsg->file));
1165 ast_copy_string(logmsg->function, function, sizeof(logmsg->function));
1166 logmsg->process_id = (long) GETTID();
1168 /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1169 if (logthread != AST_PTHREADT_NULL) {
1170 AST_LIST_LOCK(&logmsgs);
1171 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1172 ast_cond_signal(&logcond);
1173 AST_LIST_UNLOCK(&logmsgs);
1175 logger_print_normal(logmsg);
1184 struct ast_bt *ast_bt_create(void)
1186 struct ast_bt *bt = ast_calloc(1, sizeof(*bt));
1188 ast_log(LOG_ERROR, "Unable to allocate memory for backtrace structure!\n");
1194 ast_bt_get_addresses(bt);
1199 int ast_bt_get_addresses(struct ast_bt *bt)
1201 bt->num_frames = backtrace(bt->addresses, AST_MAX_BT_FRAMES);
1206 void *ast_bt_destroy(struct ast_bt *bt)
1215 #endif /* HAVE_BKTR */
1217 void ast_backtrace(void)
1224 if (!(bt = ast_bt_create())) {
1225 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
1229 if ((strings = backtrace_symbols(bt->addresses, bt->num_frames))) {
1230 ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
1231 for (i = 0; i < bt->num_frames; i++) {
1232 ast_log(LOG_DEBUG, "#%d: [%p] %s\n", i, bt->addresses[i], strings[i]);
1236 ast_debug(1, "Could not allocate memory for backtrace\n");
1240 ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1244 void __ast_verbose_ap(const char *file, int line, const char *func, const char *fmt, va_list ap)
1246 struct logmsg *logmsg = NULL;
1247 struct ast_str *buf = NULL;
1250 if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
1253 if (ast_opt_timestamp) {
1260 ast_localtime(&now, &tm, NULL);
1261 ast_strftime(date, sizeof(date), dateformat, &tm);
1262 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1263 sprintf(datefmt, "%c[%s] %s", 127, date, fmt);
1266 char *tmp = alloca(strlen(fmt) + 2);
1267 sprintf(tmp, "%c%s", 127, fmt);
1272 res = ast_str_set_va(&buf, 0, fmt, ap);
1274 /* If the build failed then we can drop this allocated message */
1275 if (res == AST_DYNSTR_BUILD_FAILED)
1278 if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1281 strcpy(logmsg->str, ast_str_buffer(buf));
1283 ast_log(__LOG_VERBOSE, file, line, func, "%s", logmsg->str + 1);
1286 logmsg->type = LOGMSG_VERBOSE;
1288 /* Add to the list and poke the thread if possible */
1289 if (logthread != AST_PTHREADT_NULL) {
1290 AST_LIST_LOCK(&logmsgs);
1291 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1292 ast_cond_signal(&logcond);
1293 AST_LIST_UNLOCK(&logmsgs);
1295 logger_print_verbose(logmsg);
1300 void __ast_verbose(const char *file, int line, const char *func, const char *fmt, ...)
1304 __ast_verbose_ap(file, line, func, fmt, ap);
1308 /* No new code should use this directly, but we have the ABI for backwards compat */
1310 void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
1311 void ast_verbose(const char *fmt, ...)
1315 __ast_verbose_ap("", 0, "", fmt, ap);
1319 int ast_register_verbose(void (*v)(const char *string))
1323 if (!(verb = ast_malloc(sizeof(*verb))))
1328 AST_RWLIST_WRLOCK(&verbosers);
1329 AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1330 AST_RWLIST_UNLOCK(&verbosers);
1335 int ast_unregister_verbose(void (*v)(const char *string))
1339 AST_RWLIST_WRLOCK(&verbosers);
1340 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1341 if (cur->verboser == v) {
1342 AST_RWLIST_REMOVE_CURRENT(list);
1347 AST_RWLIST_TRAVERSE_SAFE_END;
1348 AST_RWLIST_UNLOCK(&verbosers);
1350 return cur ? 0 : -1;