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>
30 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
32 /* When we include logger.h again it will trample on some stuff in syslog.h, but
33 * nothing we care about in here. */
36 #include "asterisk/_private.h"
37 #include "asterisk/paths.h" /* use ast_config_AST_LOG_DIR */
38 #include "asterisk/logger.h"
39 #include "asterisk/lock.h"
40 #include "asterisk/channel.h"
41 #include "asterisk/config.h"
42 #include "asterisk/term.h"
43 #include "asterisk/cli.h"
44 #include "asterisk/utils.h"
45 #include "asterisk/manager.h"
46 #include "asterisk/threadstorage.h"
47 #include "asterisk/strings.h"
48 #include "asterisk/pbx.h"
49 #include "asterisk/app.h"
50 #include "asterisk/syslog.h"
58 #define MAX_BACKTRACE_FRAMES 20
61 #if defined(__linux__) && !defined(__NR_gettid)
62 #include <asm/unistd.h>
65 #if defined(__linux__) && defined(__NR_gettid)
66 #define GETTID() syscall(__NR_gettid)
68 #define GETTID() getpid()
70 static char dateformat[256] = "%b %e %T"; /* Original Asterisk Format */
72 static char queue_log_name[256] = QUEUELOG;
73 static char exec_after_rotate[256] = "";
75 static int filesize_reload_needed;
76 static unsigned int global_logmask = 0xFFFF;
78 static enum rotatestrategy {
79 SEQUENTIAL = 1 << 0, /* Original method - create a new file, in order */
80 ROTATE = 1 << 1, /* Rotate all files, such that the oldest file has the highest suffix */
81 TIMESTAMP = 1 << 2, /* Append the epoch timestamp onto the end of the archived file */
82 } rotatestrategy = SEQUENTIAL;
85 unsigned int queue_log:1;
88 static char hostname[MAXHOSTNAMELEN];
97 /*! What to log to this channel */
99 /*! If this channel is disabled or not */
101 /*! syslog facility */
103 /*! Type of log channel */
105 /*! logfile logging file pointer */
108 char filename[PATH_MAX];
109 /*! field for linking to list */
110 AST_LIST_ENTRY(logchannel) list;
111 /*! Line number from configuration file */
113 /*! Components (levels) from last config load */
117 static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
125 enum logmsgtypes type;
129 AST_DECLARE_STRING_FIELDS(
130 AST_STRING_FIELD(date);
131 AST_STRING_FIELD(file);
132 AST_STRING_FIELD(function);
133 AST_STRING_FIELD(message);
134 AST_STRING_FIELD(level_name);
136 AST_LIST_ENTRY(logmsg) list;
139 static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
140 static pthread_t logthread = AST_PTHREADT_NULL;
141 static ast_cond_t logcond;
142 static int close_logger_thread = 0;
146 /*! \brief Logging channels used in the Asterisk logging system
148 * The first 16 levels are reserved for system usage, and the remaining
149 * levels are reserved for usage by dynamic levels registered via
150 * ast_logger_register_level.
153 /* Modifications to this array are protected by the rwlock in the
157 static char *levels[32] = {
159 "---EVENT---", /* no longer used */
167 /*! \brief Colors used in the console for logging */
168 static const int colors[32] = {
170 COLOR_BRBLUE, /* no longer used */
203 AST_THREADSTORAGE(verbose_buf);
204 #define VERBOSE_BUF_INIT_SIZE 256
206 AST_THREADSTORAGE(log_buf);
207 #define LOG_BUF_INIT_SIZE 256
209 static unsigned int make_components(const char *s, int lineno)
212 unsigned int res = 0;
213 char *stringp = ast_strdupa(s);
216 while ((w = strsep(&stringp, ","))) {
217 w = ast_skip_blanks(w);
219 if (!strcmp(w, "*")) {
222 } else for (x = 0; x < ARRAY_LEN(levels); x++) {
223 if (levels[x] && !strcasecmp(w, levels[x])) {
233 static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno)
235 struct logchannel *chan;
238 if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan) + strlen(components) + 1)))
241 strcpy(chan->components, components);
242 chan->lineno = lineno;
244 if (!strcasecmp(channel, "console")) {
245 chan->type = LOGTYPE_CONSOLE;
246 } else if (!strncasecmp(channel, "syslog", 6)) {
249 * syslog.facility => level,level,level
251 facility = strchr(channel, '.');
252 if (!facility++ || !facility) {
256 chan->facility = ast_syslog_facility(facility);
258 if (chan->facility < 0) {
259 fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
264 chan->type = LOGTYPE_SYSLOG;
265 ast_copy_string(chan->filename, channel, sizeof(chan->filename));
266 openlog("asterisk", LOG_PID, chan->facility);
268 if (!ast_strlen_zero(hostname)) {
269 snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s",
270 channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel, hostname);
272 snprintf(chan->filename, sizeof(chan->filename), "%s/%s",
273 channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel);
275 if (!(chan->fileptr = fopen(chan->filename, "a"))) {
276 /* Can't log here, since we're called with a lock */
277 fprintf(stderr, "Logger Warning: Unable to open log file '%s': %s\n", chan->filename, strerror(errno));
279 chan->type = LOGTYPE_FILE;
281 chan->logmask = make_components(chan->components, lineno);
286 static void init_logger_chain(int locked)
288 struct logchannel *chan;
289 struct ast_config *cfg;
290 struct ast_variable *var;
292 struct ast_flags config_flags = { 0 };
294 if (!(cfg = ast_config_load2("logger.conf", "logger", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID)
297 /* delete our list of log channels */
299 AST_RWLIST_WRLOCK(&logchannels);
300 while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list)))
304 AST_RWLIST_UNLOCK(&logchannels);
310 /* If no config file, we're fine, set default options. */
313 fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
315 fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
316 if (!(chan = ast_calloc(1, sizeof(*chan))))
318 chan->type = LOGTYPE_CONSOLE;
319 chan->logmask = __LOG_WARNING | __LOG_NOTICE | __LOG_ERROR;
321 AST_RWLIST_WRLOCK(&logchannels);
322 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
323 global_logmask |= chan->logmask;
325 AST_RWLIST_UNLOCK(&logchannels);
329 if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
331 if (gethostname(hostname, sizeof(hostname) - 1)) {
332 ast_copy_string(hostname, "unknown", sizeof(hostname));
333 fprintf(stderr, "What box has no hostname???\n");
339 if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
340 ast_copy_string(dateformat, s, sizeof(dateformat));
342 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
343 if ((s = ast_variable_retrieve(cfg, "general", "queue_log")))
344 logfiles.queue_log = ast_true(s);
345 if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name")))
346 ast_copy_string(queue_log_name, s, sizeof(queue_log_name));
347 if ((s = ast_variable_retrieve(cfg, "general", "exec_after_rotate")))
348 ast_copy_string(exec_after_rotate, s, sizeof(exec_after_rotate));
349 if ((s = ast_variable_retrieve(cfg, "general", "rotatestrategy"))) {
350 if (strcasecmp(s, "timestamp") == 0)
351 rotatestrategy = TIMESTAMP;
352 else if (strcasecmp(s, "rotate") == 0)
353 rotatestrategy = ROTATE;
354 else if (strcasecmp(s, "sequential") == 0)
355 rotatestrategy = SEQUENTIAL;
357 fprintf(stderr, "Unknown rotatestrategy: %s\n", s);
359 if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp"))) {
360 rotatestrategy = ast_true(s) ? TIMESTAMP : SEQUENTIAL;
361 fprintf(stderr, "rotatetimestamp option has been deprecated. Please use rotatestrategy instead.\n");
366 AST_RWLIST_WRLOCK(&logchannels);
367 var = ast_variable_browse(cfg, "logfiles");
368 for (; var; var = var->next) {
369 if (!(chan = make_logchannel(var->name, var->value, var->lineno)))
371 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
372 global_logmask |= chan->logmask;
375 AST_RWLIST_UNLOCK(&logchannels);
377 ast_config_destroy(cfg);
380 void ast_child_verbose(int level, const char *fmt, ...)
382 char *msg = NULL, *emsg = NULL, *sptr, *eptr;
386 /* Don't bother, if the level isn't that high */
387 if (option_verbose < level) {
393 if ((size = vsnprintf(msg, 0, fmt, ap)) < 0) {
400 if (!(msg = ast_malloc(size + 1))) {
405 vsnprintf(msg, size + 1, fmt, aq);
408 if (!(emsg = ast_malloc(size * 2 + 1))) {
413 for (sptr = msg, eptr = emsg; ; sptr++) {
424 fprintf(stdout, "verbose \"%s\" %d\n", emsg, level);
429 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
436 if (ast_check_realtime("queue_log")) {
438 vsnprintf(qlog_msg, sizeof(qlog_msg), fmt, ap);
440 snprintf(time_str, sizeof(time_str), "%ld", (long)time(NULL));
441 ast_store_realtime("queue_log", "time", time_str,
443 "queuename", queuename,
451 qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
452 vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
455 AST_RWLIST_RDLOCK(&logchannels);
457 fprintf(qlog, "%s\n", qlog_msg);
460 AST_RWLIST_UNLOCK(&logchannels);
464 static int rotate_file(const char *filename)
468 int x, y, which, found, res = 0, fd;
469 char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
471 switch (rotatestrategy) {
474 snprintf(new, sizeof(new), "%s.%d", filename, x);
475 fd = open(new, O_RDONLY);
481 if (rename(filename, new)) {
482 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
487 snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
488 if (rename(filename, new)) {
489 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
494 /* Find the next empty slot, including a possible suffix */
497 for (which = 0; which < ARRAY_LEN(suffixes); which++) {
498 snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
499 fd = open(new, O_RDONLY);
511 /* Found an empty slot */
512 for (y = x; y > 0; y--) {
513 for (which = 0; which < ARRAY_LEN(suffixes); which++) {
514 snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
515 fd = open(old, O_RDONLY);
517 /* Found the right suffix */
519 snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
520 if (rename(old, new)) {
521 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
529 /* Finally, rename the current file */
530 snprintf(new, sizeof(new), "%s.0", filename);
531 if (rename(filename, new)) {
532 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
537 if (!ast_strlen_zero(exec_after_rotate)) {
538 struct ast_channel *c = ast_dummy_channel_alloc();
540 pbx_builtin_setvar_helper(c, "filename", filename);
541 pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
542 if (ast_safe_system(buf) == -1) {
543 ast_log(LOG_WARNING, "error executing '%s'\n", buf);
545 c = ast_channel_release(c);
550 static int reload_logger(int rotate)
552 char old[PATH_MAX] = "";
553 int queue_rotate = rotate;
554 struct logchannel *f;
558 AST_RWLIST_WRLOCK(&logchannels);
562 /* Check filesize - this one typically doesn't need an auto-rotate */
563 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
564 if (stat(old, &st) != 0 || st.st_size > 0x40000000) { /* Arbitrarily, 1 GB */
576 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
578 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
580 f->disabled = 0; /* Re-enable logging at reload */
581 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
583 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
584 fclose(f->fileptr); /* Close file */
587 rotate_file(f->filename);
591 filesize_reload_needed = 0;
593 init_logger_chain(1 /* locked */);
595 if (logfiles.queue_log) {
596 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
600 qlog = fopen(old, "a");
602 AST_RWLIST_UNLOCK(&logchannels);
603 ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
604 AST_RWLIST_WRLOCK(&logchannels);
605 ast_verb(1, "Asterisk Queue Logger restarted\n");
607 ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
612 AST_RWLIST_UNLOCK(&logchannels);
617 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
618 a full Asterisk reload) */
619 int logger_reload(void)
622 return RESULT_FAILURE;
623 return RESULT_SUCCESS;
626 static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
630 e->command = "logger reload";
632 "Usage: logger reload\n"
633 " Reloads the logger subsystem state. Use after restarting syslogd(8) if you are using syslog logging.\n";
638 if (reload_logger(0)) {
639 ast_cli(a->fd, "Failed to reload the logger\n");
645 static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
649 e->command = "logger rotate";
651 "Usage: logger rotate\n"
652 " Rotates and Reopens the log files.\n";
657 if (reload_logger(1)) {
658 ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
664 static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
672 e->command = "logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}";
674 "Usage: logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}\n"
675 " Set a specific log level to enabled/disabled for this console.\n";
682 return CLI_SHOWUSAGE;
684 AST_RWLIST_WRLOCK(&logchannels);
686 for (x = 0; x < ARRAY_LEN(levels); x++) {
687 if (levels[x] && !strcasecmp(a->argv[3], levels[x])) {
693 AST_RWLIST_UNLOCK(&logchannels);
695 state = ast_true(a->argv[4]) ? 1 : 0;
698 ast_console_toggle_loglevel(a->fd, level, state);
699 ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
701 return CLI_SHOWUSAGE;
706 /*! \brief CLI command to show logging system configuration */
707 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
709 #define FORMATL "%-35.35s %-8.8s %-9.9s "
710 struct logchannel *chan;
713 e->command = "logger show channels";
715 "Usage: logger show channels\n"
716 " List configured logger channels.\n";
721 ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
722 ast_cli(a->fd, "Configuration\n");
723 ast_cli(a->fd, FORMATL, "-------", "----", "------");
724 ast_cli(a->fd, "-------------\n");
725 AST_RWLIST_RDLOCK(&logchannels);
726 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
729 ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
730 chan->disabled ? "Disabled" : "Enabled");
731 ast_cli(a->fd, " - ");
732 for (level = 0; level < ARRAY_LEN(levels); level++) {
733 if (chan->logmask & (1 << level)) {
734 ast_cli(a->fd, "%s ", levels[level]);
737 ast_cli(a->fd, "\n");
739 AST_RWLIST_UNLOCK(&logchannels);
740 ast_cli(a->fd, "\n");
746 void (*verboser)(const char *string);
747 AST_LIST_ENTRY(verb) list;
750 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
752 static struct ast_cli_entry cli_logger[] = {
753 AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
754 AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
755 AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
756 AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console")
759 static int handle_SIGXFSZ(int sig)
761 /* Indicate need to reload */
762 filesize_reload_needed = 1;
766 static void ast_log_vsyslog(struct logmsg *msg)
769 int syslog_level = ast_syslog_priority_from_loglevel(msg->level);
771 if (syslog_level < 0) {
772 /* we are locked here, so cannot ast_log() */
773 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", msg->level);
777 if (msg->level == __LOG_VERBOSE) {
778 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: %s", msg->process_id, msg->message);
779 msg->level = __LOG_DEBUG;
780 } else if (msg->level == __LOG_DTMF) {
781 snprintf(buf, sizeof(buf), "DTMF[%ld]: %s", msg->process_id, msg->message);
782 msg->level = __LOG_DEBUG;
784 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: %s",
785 levels[msg->level], msg->process_id, msg->file, msg->line, msg->function, msg->message);
788 term_strip(buf, buf, strlen(buf) + 1);
789 syslog(syslog_level, "%s", buf);
792 /*! \brief Print a normal log message to the channels */
793 static void logger_print_normal(struct logmsg *logmsg)
795 struct logchannel *chan = NULL;
798 AST_RWLIST_RDLOCK(&logchannels);
800 if (!AST_RWLIST_EMPTY(&logchannels)) {
801 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
802 /* If the channel is disabled, then move on to the next one */
805 /* Check syslog channels */
806 if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
807 ast_log_vsyslog(logmsg);
808 /* Console channels */
809 } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
811 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
813 /* If the level is verbose, then skip it */
814 if (logmsg->level == __LOG_VERBOSE)
817 /* Turn the numerical line number into a string */
818 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
819 /* Build string to print out */
820 snprintf(buf, sizeof(buf), "[%s] %s[%ld]: %s:%s %s: %s",
822 term_color(tmp1, logmsg->level_name, colors[logmsg->level], 0, sizeof(tmp1)),
824 term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
825 term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
826 term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
829 ast_console_puts_mutable(buf, logmsg->level);
831 } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
834 /* If no file pointer exists, skip it */
835 if (!chan->fileptr) {
839 /* Print out to the file */
840 res = fprintf(chan->fileptr, "[%s] %s[%ld] %s: %s",
841 logmsg->date, logmsg->level_name, logmsg->process_id, logmsg->file, term_strip(buf, logmsg->message, BUFSIZ));
842 if (res <= 0 && !ast_strlen_zero(logmsg->message)) {
843 fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
844 if (errno == ENOMEM || errno == ENOSPC)
845 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
847 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
848 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
850 } else if (res > 0) {
851 fflush(chan->fileptr);
855 } else if (logmsg->level != __LOG_VERBOSE) {
856 fputs(logmsg->message, stdout);
859 AST_RWLIST_UNLOCK(&logchannels);
861 /* If we need to reload because of the file size, then do so */
862 if (filesize_reload_needed) {
864 ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
870 /*! \brief Print a verbose message to the verbosers */
871 static void logger_print_verbose(struct logmsg *logmsg)
873 struct verb *v = NULL;
875 /* Iterate through the list of verbosers and pass them the log message string */
876 AST_RWLIST_RDLOCK(&verbosers);
877 AST_RWLIST_TRAVERSE(&verbosers, v, list)
878 v->verboser(logmsg->message);
879 AST_RWLIST_UNLOCK(&verbosers);
884 /*! \brief Actual logging thread */
885 static void *logger_thread(void *data)
887 struct logmsg *next = NULL, *msg = NULL;
890 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
891 AST_LIST_LOCK(&logmsgs);
892 if (AST_LIST_EMPTY(&logmsgs)) {
893 if (close_logger_thread) {
896 ast_cond_wait(&logcond, &logmsgs.lock);
899 next = AST_LIST_FIRST(&logmsgs);
900 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
901 AST_LIST_UNLOCK(&logmsgs);
903 /* Otherwise go through and process each message in the order added */
904 while ((msg = next)) {
905 /* Get the next entry now so that we can free our current structure later */
906 next = AST_LIST_NEXT(msg, list);
908 /* Depending on the type, send it to the proper function */
909 if (msg->type == LOGMSG_NORMAL)
910 logger_print_normal(msg);
911 else if (msg->type == LOGMSG_VERBOSE)
912 logger_print_verbose(msg);
914 /* Free the data since we are done */
918 /* If we should stop, then stop */
919 if (close_logger_thread)
926 int init_logger(void)
931 /* auto rotate if sig SIGXFSZ comes a-knockin */
932 (void) signal(SIGXFSZ, (void *) handle_SIGXFSZ);
934 /* start logger thread */
935 ast_cond_init(&logcond, NULL);
936 if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
937 ast_cond_destroy(&logcond);
941 /* register the logger cli commands */
942 ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
944 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
946 /* create log channels */
947 init_logger_chain(0 /* locked */);
949 if (logfiles.queue_log) {
950 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
951 qlog = fopen(tmp, "a");
952 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
957 void close_logger(void)
959 struct logchannel *f = NULL;
961 /* Stop logger thread */
962 AST_LIST_LOCK(&logmsgs);
963 close_logger_thread = 1;
964 ast_cond_signal(&logcond);
965 AST_LIST_UNLOCK(&logmsgs);
967 if (logthread != AST_PTHREADT_NULL)
968 pthread_join(logthread, NULL);
970 AST_RWLIST_WRLOCK(&logchannels);
977 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
978 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
984 closelog(); /* syslog */
986 AST_RWLIST_UNLOCK(&logchannels);
992 * \brief send log messages to syslog and/or the console
994 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
996 struct logmsg *logmsg = NULL;
997 struct ast_str *buf = NULL;
999 struct timeval now = ast_tvnow();
1002 char datestring[256];
1004 if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1007 if (AST_RWLIST_EMPTY(&logchannels)) {
1009 * we don't have the logger chain configured yet,
1010 * so just log to stdout
1012 if (level != __LOG_VERBOSE) {
1015 result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1017 if (result != AST_DYNSTR_BUILD_FAILED) {
1018 term_filter_escapes(ast_str_buffer(buf));
1019 fputs(ast_str_buffer(buf), stdout);
1025 /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
1026 are non-zero; LOG_DEBUG messages can still be displayed if option_debug
1027 is zero, if option_verbose is non-zero (this allows for 'level zero'
1028 LOG_DEBUG messages to be displayed, if the logmask on any channel
1031 if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
1034 /* Ignore anything that never gets logged anywhere */
1035 if (!(global_logmask & (1 << level)))
1040 res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1043 /* If the build failed, then abort and free this structure */
1044 if (res == AST_DYNSTR_BUILD_FAILED)
1047 /* Create a new logging message */
1048 if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
1051 /* Copy string over */
1052 ast_string_field_set(logmsg, message, ast_str_buffer(buf));
1054 /* Set type to be normal */
1055 logmsg->type = LOGMSG_NORMAL;
1057 /* Create our date/time */
1058 ast_localtime(&now, &tm, NULL);
1059 ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
1060 ast_string_field_set(logmsg, date, datestring);
1062 /* Copy over data */
1063 logmsg->level = level;
1064 logmsg->line = line;
1065 ast_string_field_set(logmsg, level_name, levels[level]);
1066 ast_string_field_set(logmsg, file, file);
1067 ast_string_field_set(logmsg, function, function);
1068 logmsg->process_id = (long) GETTID();
1070 /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1071 if (logthread != AST_PTHREADT_NULL) {
1072 AST_LIST_LOCK(&logmsgs);
1073 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1074 ast_cond_signal(&logcond);
1075 AST_LIST_UNLOCK(&logmsgs);
1077 logger_print_normal(logmsg);
1086 struct ast_bt *ast_bt_create(void)
1088 struct ast_bt *bt = ast_calloc(1, sizeof(*bt));
1090 ast_log(LOG_ERROR, "Unable to allocate memory for backtrace structure!\n");
1096 ast_bt_get_addresses(bt);
1101 int ast_bt_get_addresses(struct ast_bt *bt)
1103 bt->num_frames = backtrace(bt->addresses, AST_MAX_BT_FRAMES);
1108 void *ast_bt_destroy(struct ast_bt *bt)
1117 #endif /* HAVE_BKTR */
1119 void ast_backtrace(void)
1126 if (!(bt = ast_bt_create())) {
1127 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
1131 if ((strings = backtrace_symbols(bt->addresses, bt->num_frames))) {
1132 ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
1133 for (i = 0; i < bt->num_frames; i++) {
1134 ast_log(LOG_DEBUG, "#%d: [%p] %s\n", i, bt->addresses[i], strings[i]);
1137 /* MALLOC_DEBUG will erroneously report an error here, unless we undef the macro. */
1141 ast_debug(1, "Could not allocate memory for backtrace\n");
1145 ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1149 void __ast_verbose_ap(const char *file, int line, const char *func, const char *fmt, va_list ap)
1151 struct logmsg *logmsg = NULL;
1152 struct ast_str *buf = NULL;
1155 if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
1158 if (ast_opt_timestamp) {
1165 ast_localtime(&now, &tm, NULL);
1166 ast_strftime(date, sizeof(date), dateformat, &tm);
1167 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1168 sprintf(datefmt, "%c[%s] %s", 127, date, fmt);
1171 char *tmp = alloca(strlen(fmt) + 2);
1172 sprintf(tmp, "%c%s", 127, fmt);
1177 res = ast_str_set_va(&buf, 0, fmt, ap);
1179 /* If the build failed then we can drop this allocated message */
1180 if (res == AST_DYNSTR_BUILD_FAILED)
1183 if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
1186 ast_string_field_set(logmsg, message, ast_str_buffer(buf));
1188 ast_log(__LOG_VERBOSE, file, line, func, "%s", logmsg->message + 1);
1191 logmsg->type = LOGMSG_VERBOSE;
1193 /* Add to the list and poke the thread if possible */
1194 if (logthread != AST_PTHREADT_NULL) {
1195 AST_LIST_LOCK(&logmsgs);
1196 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1197 ast_cond_signal(&logcond);
1198 AST_LIST_UNLOCK(&logmsgs);
1200 logger_print_verbose(logmsg);
1205 void __ast_verbose(const char *file, int line, const char *func, const char *fmt, ...)
1210 __ast_verbose_ap(file, line, func, fmt, ap);
1214 /* No new code should use this directly, but we have the ABI for backwards compat */
1216 void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
1217 void ast_verbose(const char *fmt, ...)
1222 __ast_verbose_ap("", 0, "", fmt, ap);
1226 int ast_register_verbose(void (*v)(const char *string))
1230 if (!(verb = ast_malloc(sizeof(*verb))))
1235 AST_RWLIST_WRLOCK(&verbosers);
1236 AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1237 AST_RWLIST_UNLOCK(&verbosers);
1242 int ast_unregister_verbose(void (*v)(const char *string))
1246 AST_RWLIST_WRLOCK(&verbosers);
1247 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1248 if (cur->verboser == v) {
1249 AST_RWLIST_REMOVE_CURRENT(list);
1254 AST_RWLIST_TRAVERSE_SAFE_END;
1255 AST_RWLIST_UNLOCK(&verbosers);
1257 return cur ? 0 : -1;
1260 static void update_logchannels(void)
1262 struct logchannel *cur;
1264 AST_RWLIST_WRLOCK(&logchannels);
1268 AST_RWLIST_TRAVERSE(&logchannels, cur, list) {
1269 cur->logmask = make_components(cur->components, cur->lineno);
1270 global_logmask |= cur->logmask;
1273 AST_RWLIST_UNLOCK(&logchannels);
1276 int ast_logger_register_level(const char *name)
1279 unsigned int available = 0;
1281 AST_RWLIST_WRLOCK(&logchannels);
1283 for (level = 0; level < ARRAY_LEN(levels); level++) {
1284 if ((level >= 16) && !available && !levels[level]) {
1289 if (levels[level] && !strcasecmp(levels[level], name)) {
1290 ast_log(LOG_WARNING,
1291 "Unable to register dynamic logger level '%s': a standard logger level uses that name.\n",
1293 AST_RWLIST_UNLOCK(&logchannels);
1300 ast_log(LOG_WARNING,
1301 "Unable to register dynamic logger level '%s'; maximum number of levels registered.\n",
1303 AST_RWLIST_UNLOCK(&logchannels);
1308 levels[available] = ast_strdup(name);
1310 AST_RWLIST_UNLOCK(&logchannels);
1312 ast_debug(1, "Registered dynamic logger level '%s' with index %d.\n", name, available);
1314 update_logchannels();
1319 void ast_logger_unregister_level(const char *name)
1321 unsigned int found = 0;
1324 AST_RWLIST_WRLOCK(&logchannels);
1326 for (x = 16; x < ARRAY_LEN(levels); x++) {
1331 if (strcasecmp(levels[x], name)) {
1340 /* take this level out of the global_logmask, to ensure that no new log messages
1341 * will be queued for it
1344 global_logmask &= ~(1 << x);
1348 AST_RWLIST_UNLOCK(&logchannels);
1350 ast_debug(1, "Unregistered dynamic logger level '%s' with index %d.\n", name, x);
1352 update_logchannels();
1354 AST_RWLIST_UNLOCK(&logchannels);