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>
28 /*! \li \ref logger.c uses the configuration file \ref logger.conf
29 * \addtogroup configuration_file Configuration Files
33 * \page logger.conf logger.conf
34 * \verbinclude logger.conf.sample
38 <support_level>core</support_level>
43 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
45 /* When we include logger.h again it will trample on some stuff in syslog.h, but
46 * nothing we care about in here. */
49 #include "asterisk/_private.h"
50 #include "asterisk/paths.h" /* use ast_config_AST_LOG_DIR */
51 #include "asterisk/logger.h"
52 #include "asterisk/lock.h"
53 #include "asterisk/channel.h"
54 #include "asterisk/config.h"
55 #include "asterisk/term.h"
56 #include "asterisk/cli.h"
57 #include "asterisk/utils.h"
58 #include "asterisk/manager.h"
59 #include "asterisk/astobj2.h"
60 #include "asterisk/threadstorage.h"
61 #include "asterisk/strings.h"
62 #include "asterisk/pbx.h"
63 #include "asterisk/app.h"
64 #include "asterisk/syslog.h"
65 #include "asterisk/buildinfo.h"
66 #include "asterisk/ast_version.h"
74 #define MAX_BACKTRACE_FRAMES 20
75 # if defined(HAVE_DLADDR) && defined(HAVE_BFD) && defined(BETTER_BACKTRACES)
84 static char dateformat[256] = "%b %e %T"; /* Original Asterisk Format */
86 static char queue_log_name[256] = QUEUELOG;
87 static char exec_after_rotate[256] = "";
89 static int filesize_reload_needed;
90 static unsigned int global_logmask = 0xFFFF;
91 static int queuelog_init;
92 static int logger_initialized;
93 static volatile int next_unique_callid; /* Used to assign unique call_ids to calls */
94 static int display_callids;
95 static void unique_callid_cleanup(void *data);
98 int call_identifier; /* Numerical value of the call displayed in the logs */
101 AST_THREADSTORAGE_CUSTOM(unique_callid, NULL, unique_callid_cleanup);
103 static enum rotatestrategy {
104 NONE = 0, /* Do not rotate log files at all, instead rely on external mechanisms */
105 SEQUENTIAL = 1 << 0, /* Original method - create a new file, in order */
106 ROTATE = 1 << 1, /* Rotate all files, such that the oldest file has the highest suffix */
107 TIMESTAMP = 1 << 2, /* Append the epoch timestamp onto the end of the archived file */
108 } rotatestrategy = SEQUENTIAL;
111 unsigned int queue_log:1;
112 unsigned int queue_log_to_file:1;
113 unsigned int queue_adaptive_realtime:1;
114 unsigned int queue_log_realtime_use_gmt:1;
117 static char hostname[MAXHOSTNAMELEN];
126 /*! What to log to this channel */
127 unsigned int logmask;
128 /*! If this channel is disabled or not */
130 /*! syslog facility */
132 /*! Verbosity level */
134 /*! Type of log channel */
136 /*! logfile logging file pointer */
139 char filename[PATH_MAX];
140 /*! field for linking to list */
141 AST_LIST_ENTRY(logchannel) list;
142 /*! Line number from configuration file */
144 /*! Components (levels) from last config load */
148 static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
156 enum logmsgtypes type;
160 struct ast_callid *callid;
161 AST_DECLARE_STRING_FIELDS(
162 AST_STRING_FIELD(date);
163 AST_STRING_FIELD(file);
164 AST_STRING_FIELD(function);
165 AST_STRING_FIELD(message);
166 AST_STRING_FIELD(level_name);
168 AST_LIST_ENTRY(logmsg) list;
171 static void logmsg_free(struct logmsg *msg)
174 ast_callid_unref(msg->callid);
179 static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
180 static pthread_t logthread = AST_PTHREADT_NULL;
181 static ast_cond_t logcond;
182 static int close_logger_thread = 0;
186 /*! \brief Logging channels used in the Asterisk logging system
188 * The first 16 levels are reserved for system usage, and the remaining
189 * levels are reserved for usage by dynamic levels registered via
190 * ast_logger_register_level.
193 /* Modifications to this array are protected by the rwlock in the
197 static char *levels[NUMLOGLEVELS] = {
199 "---EVENT---", /* no longer used */
207 /*! \brief Colors used in the console for logging */
208 static const int colors[NUMLOGLEVELS] = {
210 COLOR_BRBLUE, /* no longer used */
243 AST_THREADSTORAGE(verbose_buf);
244 #define VERBOSE_BUF_INIT_SIZE 256
246 AST_THREADSTORAGE(log_buf);
247 #define LOG_BUF_INIT_SIZE 256
249 static void logger_queue_init(void);
251 static unsigned int make_components(const char *s, int lineno, int *verbosity)
254 unsigned int res = 0;
255 char *stringp = ast_strdupa(s);
260 while ((w = strsep(&stringp, ","))) {
261 w = ast_skip_blanks(w);
263 if (!strcmp(w, "*")) {
266 } else if (!strncasecmp(w, "verbose(", 8) && sscanf(w + 8, "%d)", verbosity) == 1) {
267 res |= (1 << __LOG_VERBOSE);
269 } else for (x = 0; x < ARRAY_LEN(levels); x++) {
270 if (levels[x] && !strcasecmp(w, levels[x])) {
280 static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno)
282 struct logchannel *chan;
285 struct timeval now = ast_tvnow();
286 char datestring[256];
288 if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan) + strlen(components) + 1)))
291 strcpy(chan->components, components);
292 chan->lineno = lineno;
294 if (!strcasecmp(channel, "console")) {
295 chan->type = LOGTYPE_CONSOLE;
296 } else if (!strncasecmp(channel, "syslog", 6)) {
299 * syslog.facility => level,level,level
301 facility = strchr(channel, '.');
302 if (!facility++ || !facility) {
306 chan->facility = ast_syslog_facility(facility);
308 if (chan->facility < 0) {
309 fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
314 chan->type = LOGTYPE_SYSLOG;
315 ast_copy_string(chan->filename, channel, sizeof(chan->filename));
316 openlog("asterisk", LOG_PID, chan->facility);
318 if (!ast_strlen_zero(hostname)) {
319 snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s",
320 channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel, hostname);
322 snprintf(chan->filename, sizeof(chan->filename), "%s/%s",
323 channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel);
325 if (!(chan->fileptr = fopen(chan->filename, "a"))) {
326 /* Can't do real logging here since we're called with a lock
327 * so log to any attached consoles */
328 ast_console_puts_mutable("ERROR: Unable to open log file '", __LOG_ERROR);
329 ast_console_puts_mutable(chan->filename, __LOG_ERROR);
330 ast_console_puts_mutable("': ", __LOG_ERROR);
331 ast_console_puts_mutable(strerror(errno), __LOG_ERROR);
332 ast_console_puts_mutable("'\n", __LOG_ERROR);
336 /* Create our date/time */
337 ast_localtime(&now, &tm, NULL);
338 ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
340 fprintf(chan->fileptr, "[%s] Asterisk %s built by %s @ %s on a %s running %s on %s\n",
341 datestring, ast_get_version(), ast_build_user, ast_build_hostname,
342 ast_build_machine, ast_build_os, ast_build_date);
343 fflush(chan->fileptr);
345 chan->type = LOGTYPE_FILE;
347 chan->logmask = make_components(chan->components, lineno, &chan->verbosity);
352 static void init_logger_chain(int locked, const char *altconf)
354 struct logchannel *chan;
355 struct ast_config *cfg;
356 struct ast_variable *var;
358 struct ast_flags config_flags = { 0 };
362 if (!(cfg = ast_config_load2(S_OR(altconf, "logger.conf"), "logger", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID) {
366 /* delete our list of log channels */
368 AST_RWLIST_WRLOCK(&logchannels);
370 while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list))) {
375 AST_RWLIST_UNLOCK(&logchannels);
382 /* If no config file, we're fine, set default options. */
385 fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
387 fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
389 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
392 chan->type = LOGTYPE_CONSOLE;
393 chan->logmask = __LOG_WARNING | __LOG_NOTICE | __LOG_ERROR;
395 AST_RWLIST_WRLOCK(&logchannels);
397 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
398 global_logmask |= chan->logmask;
400 AST_RWLIST_UNLOCK(&logchannels);
405 if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
407 if (gethostname(hostname, sizeof(hostname) - 1)) {
408 ast_copy_string(hostname, "unknown", sizeof(hostname));
409 fprintf(stderr, "What box has no hostname???\n");
415 if ((s = ast_variable_retrieve(cfg, "general", "display_callids"))) {
416 display_callids = ast_true(s);
418 if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
419 ast_copy_string(dateformat, s, sizeof(dateformat));
421 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
422 if ((s = ast_variable_retrieve(cfg, "general", "queue_log"))) {
423 logfiles.queue_log = ast_true(s);
425 if ((s = ast_variable_retrieve(cfg, "general", "queue_log_to_file"))) {
426 logfiles.queue_log_to_file = ast_true(s);
428 if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name"))) {
429 ast_copy_string(queue_log_name, s, sizeof(queue_log_name));
431 if ((s = ast_variable_retrieve(cfg, "general", "queue_log_realtime_use_gmt"))) {
432 logfiles.queue_log_realtime_use_gmt = ast_true(s);
434 if ((s = ast_variable_retrieve(cfg, "general", "exec_after_rotate"))) {
435 ast_copy_string(exec_after_rotate, s, sizeof(exec_after_rotate));
437 if ((s = ast_variable_retrieve(cfg, "general", "rotatestrategy"))) {
438 if (strcasecmp(s, "timestamp") == 0) {
439 rotatestrategy = TIMESTAMP;
440 } else if (strcasecmp(s, "rotate") == 0) {
441 rotatestrategy = ROTATE;
442 } else if (strcasecmp(s, "sequential") == 0) {
443 rotatestrategy = SEQUENTIAL;
444 } else if (strcasecmp(s, "none") == 0) {
445 rotatestrategy = NONE;
447 fprintf(stderr, "Unknown rotatestrategy: %s\n", s);
450 if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp"))) {
451 rotatestrategy = ast_true(s) ? TIMESTAMP : SEQUENTIAL;
452 fprintf(stderr, "rotatetimestamp option has been deprecated. Please use rotatestrategy instead.\n");
457 AST_RWLIST_WRLOCK(&logchannels);
459 var = ast_variable_browse(cfg, "logfiles");
460 for (; var; var = var->next) {
461 if (!(chan = make_logchannel(var->name, var->value, var->lineno))) {
462 /* Print error message directly to the consoles since the lock is held
463 * and we don't want to unlock with the list partially built */
464 ast_console_puts_mutable("ERROR: Unable to create log channel '", __LOG_ERROR);
465 ast_console_puts_mutable(var->name, __LOG_ERROR);
466 ast_console_puts_mutable("'\n", __LOG_ERROR);
469 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
470 global_logmask |= chan->logmask;
479 AST_RWLIST_UNLOCK(&logchannels);
482 ast_config_destroy(cfg);
485 void ast_child_verbose(int level, const char *fmt, ...)
487 char *msg = NULL, *emsg = NULL, *sptr, *eptr;
493 if ((size = vsnprintf(msg, 0, fmt, ap)) < 0) {
500 if (!(msg = ast_malloc(size + 1))) {
505 vsnprintf(msg, size + 1, fmt, aq);
508 if (!(emsg = ast_malloc(size * 2 + 1))) {
513 for (sptr = msg, eptr = emsg; ; sptr++) {
524 fprintf(stdout, "verbose \"%s\" %d\n", emsg, level);
529 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
538 if (!logger_initialized) {
539 /* You are too early. We are not open yet! */
542 if (!queuelog_init) {
543 AST_RWLIST_WRLOCK(&logchannels);
544 if (!queuelog_init) {
546 * We have delayed initializing the queue logging system so
547 * preloaded realtime modules can get up. We must initialize
548 * now since someone is trying to log something.
552 AST_RWLIST_UNLOCK(&logchannels);
553 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
555 AST_RWLIST_UNLOCK(&logchannels);
559 if (ast_check_realtime("queue_log")) {
561 ast_localtime(&tv, &tm, logfiles.queue_log_realtime_use_gmt ? "GMT" : NULL);
562 ast_strftime(time_str, sizeof(time_str), "%F %T.%6q", &tm);
564 vsnprintf(qlog_msg, sizeof(qlog_msg), fmt, ap);
566 if (logfiles.queue_adaptive_realtime) {
567 AST_DECLARE_APP_ARGS(args,
568 AST_APP_ARG(data)[5];
570 AST_NONSTANDARD_APP_ARGS(args, qlog_msg, '|');
571 /* Ensure fields are large enough to receive data */
572 ast_realtime_require_field("queue_log",
573 "data1", RQ_CHAR, strlen(S_OR(args.data[0], "")),
574 "data2", RQ_CHAR, strlen(S_OR(args.data[1], "")),
575 "data3", RQ_CHAR, strlen(S_OR(args.data[2], "")),
576 "data4", RQ_CHAR, strlen(S_OR(args.data[3], "")),
577 "data5", RQ_CHAR, strlen(S_OR(args.data[4], "")),
581 ast_store_realtime("queue_log", "time", time_str,
583 "queuename", queuename,
586 "data1", S_OR(args.data[0], ""),
587 "data2", S_OR(args.data[1], ""),
588 "data3", S_OR(args.data[2], ""),
589 "data4", S_OR(args.data[3], ""),
590 "data5", S_OR(args.data[4], ""),
593 ast_store_realtime("queue_log", "time", time_str,
595 "queuename", queuename,
602 if (!logfiles.queue_log_to_file) {
609 qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
610 vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
612 AST_RWLIST_RDLOCK(&logchannels);
614 fprintf(qlog, "%s\n", qlog_msg);
617 AST_RWLIST_UNLOCK(&logchannels);
621 static int rotate_file(const char *filename)
625 int x, y, which, found, res = 0, fd;
626 char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
628 switch (rotatestrategy) {
634 snprintf(new, sizeof(new), "%s.%d", filename, x);
635 fd = open(new, O_RDONLY);
641 if (rename(filename, new)) {
642 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
649 snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
650 if (rename(filename, new)) {
651 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
658 /* Find the next empty slot, including a possible suffix */
661 for (which = 0; which < ARRAY_LEN(suffixes); which++) {
662 snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
663 fd = open(new, O_RDONLY);
675 /* Found an empty slot */
676 for (y = x; y > 0; y--) {
677 for (which = 0; which < ARRAY_LEN(suffixes); which++) {
678 snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
679 fd = open(old, O_RDONLY);
681 /* Found the right suffix */
683 snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
684 if (rename(old, new)) {
685 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
693 /* Finally, rename the current file */
694 snprintf(new, sizeof(new), "%s.0", filename);
695 if (rename(filename, new)) {
696 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
703 if (!ast_strlen_zero(exec_after_rotate)) {
704 struct ast_channel *c = ast_dummy_channel_alloc();
707 pbx_builtin_setvar_helper(c, "filename", filename);
708 pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
710 c = ast_channel_unref(c);
712 if (ast_safe_system(buf) == -1) {
713 ast_log(LOG_WARNING, "error executing '%s'\n", buf);
721 * \brief Start the realtime queue logging if configured.
723 * \retval TRUE if not to open queue log file.
725 static int logger_queue_rt_start(void)
727 if (ast_check_realtime("queue_log")) {
728 if (!ast_realtime_require_field("queue_log",
729 "time", RQ_DATETIME, 26,
730 "data1", RQ_CHAR, 20,
731 "data2", RQ_CHAR, 20,
732 "data3", RQ_CHAR, 20,
733 "data4", RQ_CHAR, 20,
734 "data5", RQ_CHAR, 20,
736 logfiles.queue_adaptive_realtime = 1;
738 logfiles.queue_adaptive_realtime = 0;
741 if (!logfiles.queue_log_to_file) {
742 /* Don't open the log file. */
751 * \brief Rotate the queue log file and restart.
753 * \param queue_rotate Log queue rotation mode.
755 * \note Assumes logchannels is write locked on entry.
757 * \retval 0 on success.
758 * \retval -1 on error.
760 static int logger_queue_restart(int queue_rotate)
763 char qfname[PATH_MAX];
765 if (logger_queue_rt_start()) {
769 snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
771 /* Just in case it was still open. */
779 /* Open the log file. */
780 qlog = fopen(qfname, "a");
782 ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
788 static int reload_logger(int rotate, const char *altconf)
790 int queue_rotate = rotate;
791 struct logchannel *f;
794 AST_RWLIST_WRLOCK(&logchannels);
798 /* Check filesize - this one typically doesn't need an auto-rotate */
799 if (ftello(qlog) > 0x40000000) { /* Arbitrarily, 1 GB */
813 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
815 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
817 f->disabled = 0; /* Re-enable logging at reload */
819 <managerEventInstance>
820 <synopsis>Raised when a logging channel is re-enabled after a reload operation.</synopsis>
822 <parameter name="Channel">
823 <para>The name of the logging channel.</para>
826 </managerEventInstance>
828 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
830 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
832 if (rotatestrategy != NONE && ftello(f->fileptr) > 0x40000000) { /* Arbitrarily, 1 GB */
833 /* Be more proactive about rotating massive log files */
836 fclose(f->fileptr); /* Close file */
838 if (rotate || rotate_this) {
839 rotate_file(f->filename);
844 filesize_reload_needed = 0;
846 init_logger_chain(1 /* locked */, altconf);
848 ast_unload_realtime("queue_log");
849 if (logfiles.queue_log) {
850 res = logger_queue_restart(queue_rotate);
851 AST_RWLIST_UNLOCK(&logchannels);
852 ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
853 ast_verb(1, "Asterisk Queue Logger restarted\n");
855 AST_RWLIST_UNLOCK(&logchannels);
861 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
862 a full Asterisk reload) */
863 int logger_reload(void)
865 if (reload_logger(0, NULL)) {
866 return RESULT_FAILURE;
868 return RESULT_SUCCESS;
871 static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
875 e->command = "logger reload";
877 "Usage: logger reload [<alt-conf>]\n"
878 " Reloads the logger subsystem state. Use after restarting syslogd(8) if you are using syslog logging.\n";
883 if (reload_logger(0, a->argc == 3 ? a->argv[2] : NULL)) {
884 ast_cli(a->fd, "Failed to reload the logger\n");
890 static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
894 e->command = "logger rotate";
896 "Usage: logger rotate\n"
897 " Rotates and Reopens the log files.\n";
902 if (reload_logger(1, NULL)) {
903 ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
909 static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
917 e->command = "logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}";
919 "Usage: logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}\n"
920 " Set a specific log level to enabled/disabled for this console.\n";
927 return CLI_SHOWUSAGE;
929 AST_RWLIST_WRLOCK(&logchannels);
931 for (x = 0; x < ARRAY_LEN(levels); x++) {
932 if (levels[x] && !strcasecmp(a->argv[3], levels[x])) {
938 AST_RWLIST_UNLOCK(&logchannels);
940 state = ast_true(a->argv[4]) ? 1 : 0;
943 ast_console_toggle_loglevel(a->fd, level, state);
944 ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
946 return CLI_SHOWUSAGE;
951 /*! \brief CLI command to show logging system configuration */
952 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
954 #define FORMATL "%-35.35s %-8.8s %-9.9s "
955 struct logchannel *chan;
958 e->command = "logger show channels";
960 "Usage: logger show channels\n"
961 " List configured logger channels.\n";
966 ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
967 ast_cli(a->fd, "Configuration\n");
968 ast_cli(a->fd, FORMATL, "-------", "----", "------");
969 ast_cli(a->fd, "-------------\n");
970 AST_RWLIST_RDLOCK(&logchannels);
971 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
974 ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
975 chan->disabled ? "Disabled" : "Enabled");
976 ast_cli(a->fd, " - ");
977 for (level = 0; level < ARRAY_LEN(levels); level++) {
978 if ((chan->logmask & (1 << level)) && levels[level]) {
979 ast_cli(a->fd, "%s ", levels[level]);
982 ast_cli(a->fd, "\n");
984 AST_RWLIST_UNLOCK(&logchannels);
985 ast_cli(a->fd, "\n");
991 void (*verboser)(const char *string);
992 AST_LIST_ENTRY(verb) list;
995 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
997 static struct ast_cli_entry cli_logger[] = {
998 AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
999 AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
1000 AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
1001 AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console")
1004 static void _handle_SIGXFSZ(int sig)
1006 /* Indicate need to reload */
1007 filesize_reload_needed = 1;
1010 static struct sigaction handle_SIGXFSZ = {
1011 .sa_handler = _handle_SIGXFSZ,
1012 .sa_flags = SA_RESTART,
1015 static void ast_log_vsyslog(struct logmsg *msg)
1018 int syslog_level = ast_syslog_priority_from_loglevel(msg->level);
1019 char call_identifier_str[13];
1022 snprintf(call_identifier_str, sizeof(call_identifier_str), "[C-%08x]", msg->callid->call_identifier);
1024 call_identifier_str[0] = '\0';
1027 if (syslog_level < 0) {
1028 /* we are locked here, so cannot ast_log() */
1029 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", msg->level);
1033 snprintf(buf, sizeof(buf), "%s[%d]%s: %s:%d in %s: %s",
1034 levels[msg->level], msg->lwp, call_identifier_str, msg->file, msg->line, msg->function, msg->message);
1036 term_strip(buf, buf, strlen(buf) + 1);
1037 syslog(syslog_level, "%s", buf);
1040 /* These gymnastics are due to platforms which designate char as unsigned by
1041 * default. Level is the negative character -- offset by 1, because \0 is the
1043 #define VERBOSE_MAGIC2LEVEL(x) (((char) -*(signed char *) (x)) - 1)
1044 #define VERBOSE_HASMAGIC(x) (*(signed char *) (x) < 0)
1046 /*! \brief Print a normal log message to the channels */
1047 static void logger_print_normal(struct logmsg *logmsg)
1049 struct logchannel *chan = NULL;
1051 struct verb *v = NULL;
1054 if (logmsg->level == __LOG_VERBOSE) {
1055 char *tmpmsg = ast_strdupa(logmsg->message + 1);
1056 level = VERBOSE_MAGIC2LEVEL(logmsg->message);
1057 /* Iterate through the list of verbosers and pass them the log message string */
1058 AST_RWLIST_RDLOCK(&verbosers);
1059 AST_RWLIST_TRAVERSE(&verbosers, v, list)
1060 v->verboser(logmsg->message);
1061 AST_RWLIST_UNLOCK(&verbosers);
1062 ast_string_field_set(logmsg, message, tmpmsg);
1065 AST_RWLIST_RDLOCK(&logchannels);
1067 if (!AST_RWLIST_EMPTY(&logchannels)) {
1068 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
1069 char call_identifier_str[13];
1071 if (logmsg->callid) {
1072 snprintf(call_identifier_str, sizeof(call_identifier_str), "[C-%08x]", logmsg->callid->call_identifier);
1074 call_identifier_str[0] = '\0';
1078 /* If the channel is disabled, then move on to the next one */
1079 if (chan->disabled) {
1082 if (logmsg->level == __LOG_VERBOSE && level > chan->verbosity) {
1086 /* Check syslog channels */
1087 if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
1088 ast_log_vsyslog(logmsg);
1089 /* Console channels */
1090 } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
1093 /* If the level is verbose, then skip it */
1094 if (logmsg->level == __LOG_VERBOSE)
1097 /* Turn the numerical line number into a string */
1098 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
1099 /* Build string to print out */
1100 snprintf(buf, sizeof(buf), "[%s] " COLORIZE_FMT "[%d]%s: " COLORIZE_FMT ":" COLORIZE_FMT " " COLORIZE_FMT ": %s",
1102 COLORIZE(colors[logmsg->level], 0, logmsg->level_name),
1104 call_identifier_str,
1105 COLORIZE(COLOR_BRWHITE, 0, logmsg->file),
1106 COLORIZE(COLOR_BRWHITE, 0, linestr),
1107 COLORIZE(COLOR_BRWHITE, 0, logmsg->function),
1110 ast_console_puts_mutable(buf, logmsg->level);
1112 } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
1115 /* If no file pointer exists, skip it */
1116 if (!chan->fileptr) {
1120 /* Print out to the file */
1121 res = fprintf(chan->fileptr, "[%s] %s[%d]%s %s: %s",
1122 logmsg->date, logmsg->level_name, logmsg->lwp, call_identifier_str,
1123 logmsg->file, term_strip(buf, logmsg->message, BUFSIZ));
1124 if (res <= 0 && !ast_strlen_zero(logmsg->message)) {
1125 fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
1126 if (errno == ENOMEM || errno == ENOSPC)
1127 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
1129 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
1131 <managerEventInstance>
1132 <synopsis>Raised when a logging channel is disabled.</synopsis>
1134 <parameter name="Channel">
1135 <para>The name of the logging channel.</para>
1138 </managerEventInstance>
1140 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
1142 } else if (res > 0) {
1143 fflush(chan->fileptr);
1147 } else if (logmsg->level != __LOG_VERBOSE) {
1148 fputs(logmsg->message, stdout);
1151 AST_RWLIST_UNLOCK(&logchannels);
1153 /* If we need to reload because of the file size, then do so */
1154 if (filesize_reload_needed) {
1155 reload_logger(-1, NULL);
1156 ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
1162 /*! \brief Actual logging thread */
1163 static void *logger_thread(void *data)
1165 struct logmsg *next = NULL, *msg = NULL;
1168 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
1169 AST_LIST_LOCK(&logmsgs);
1170 if (AST_LIST_EMPTY(&logmsgs)) {
1171 if (close_logger_thread) {
1172 AST_LIST_UNLOCK(&logmsgs);
1175 ast_cond_wait(&logcond, &logmsgs.lock);
1178 next = AST_LIST_FIRST(&logmsgs);
1179 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
1180 AST_LIST_UNLOCK(&logmsgs);
1182 /* Otherwise go through and process each message in the order added */
1183 while ((msg = next)) {
1184 /* Get the next entry now so that we can free our current structure later */
1185 next = AST_LIST_NEXT(msg, list);
1187 /* Depending on the type, send it to the proper function */
1188 logger_print_normal(msg);
1190 /* Free the data since we are done */
1194 /* If we should stop, then stop */
1195 if (close_logger_thread)
1204 * \brief Initialize the logger queue.
1206 * \note Assumes logchannels is write locked on entry.
1210 static void logger_queue_init(void)
1212 ast_unload_realtime("queue_log");
1213 if (logfiles.queue_log) {
1214 char qfname[PATH_MAX];
1216 if (logger_queue_rt_start()) {
1220 /* Open the log file. */
1221 snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR,
1224 /* Just in case it was already open. */
1227 qlog = fopen(qfname, "a");
1229 ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
1234 int init_logger(void)
1236 /* auto rotate if sig SIGXFSZ comes a-knockin */
1237 sigaction(SIGXFSZ, &handle_SIGXFSZ, NULL);
1239 /* Re-initialize the logmsgs mutex. The recursive mutex can be accessed prior
1240 * to Asterisk being forked into the background, which can cause the thread
1241 * ID tracked by the underlying pthread mutex to be different than the ID of
1242 * the thread that unlocks the mutex. Since init_logger is called after the
1243 * fork, it is safe to initialize the mutex here for future accesses.
1245 ast_mutex_destroy(&logmsgs.lock);
1246 ast_mutex_init(&logmsgs.lock);
1247 ast_cond_init(&logcond, NULL);
1249 /* start logger thread */
1250 if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
1251 ast_cond_destroy(&logcond);
1255 /* register the logger cli commands */
1256 ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
1258 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
1260 /* create log channels */
1261 init_logger_chain(0 /* locked */, NULL);
1262 logger_initialized = 1;
1267 void close_logger(void)
1269 struct logchannel *f = NULL;
1270 struct verb *cur = NULL;
1272 ast_cli_unregister_multiple(cli_logger, ARRAY_LEN(cli_logger));
1274 logger_initialized = 0;
1276 /* Stop logger thread */
1277 AST_LIST_LOCK(&logmsgs);
1278 close_logger_thread = 1;
1279 ast_cond_signal(&logcond);
1280 AST_LIST_UNLOCK(&logmsgs);
1282 if (logthread != AST_PTHREADT_NULL)
1283 pthread_join(logthread, NULL);
1285 AST_RWLIST_WRLOCK(&verbosers);
1286 while ((cur = AST_LIST_REMOVE_HEAD(&verbosers, list))) {
1289 AST_RWLIST_UNLOCK(&verbosers);
1291 AST_RWLIST_WRLOCK(&logchannels);
1298 while ((f = AST_LIST_REMOVE_HEAD(&logchannels, list))) {
1299 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
1306 closelog(); /* syslog */
1308 AST_RWLIST_UNLOCK(&logchannels);
1311 void ast_callid_strnprint(char *buffer, size_t buffer_size, struct ast_callid *callid)
1313 snprintf(buffer, buffer_size, "[C-%08x]", callid->call_identifier);
1316 struct ast_callid *ast_create_callid(void)
1318 struct ast_callid *call;
1320 call = ao2_alloc_options(sizeof(struct ast_callid), NULL, AO2_ALLOC_OPT_LOCK_NOLOCK);
1322 ast_log(LOG_ERROR, "Could not allocate callid struct.\n");
1326 call->call_identifier = ast_atomic_fetchadd_int(&next_unique_callid, +1);
1327 #ifdef TEST_FRAMEWORK
1328 ast_debug(3, "CALL_ID [C-%08x] created by thread.\n", call->call_identifier);
1333 struct ast_callid *ast_read_threadstorage_callid(void)
1335 struct ast_callid **callid;
1336 callid = ast_threadstorage_get(&unique_callid, sizeof(struct ast_callid **));
1337 if (callid && *callid) {
1338 ast_callid_ref(*callid);
1346 int ast_callid_threadassoc_change(struct ast_callid *callid)
1348 struct ast_callid **id =
1349 ast_threadstorage_get(&unique_callid, sizeof(struct ast_callid **));
1352 ast_log(LOG_ERROR, "Failed to allocate thread storage.\n");
1356 if (*id && (*id != callid)) {
1357 #ifdef TEST_FRAMEWORK
1358 ast_debug(3, "CALL_ID [C-%08x] being removed from thread.\n", (*id)->call_identifier);
1360 *id = ast_callid_unref(*id);
1364 if (!(*id) && callid) {
1365 /* callid will be unreffed at thread destruction */
1366 ast_callid_ref(callid);
1368 #ifdef TEST_FRAMEWORK
1369 ast_debug(3, "CALL_ID [C-%08x] bound to thread.\n", callid->call_identifier);
1376 int ast_callid_threadassoc_add(struct ast_callid *callid)
1378 struct ast_callid **pointing;
1379 pointing = ast_threadstorage_get(&unique_callid, sizeof(struct ast_callid **));
1381 ast_log(LOG_ERROR, "Failed to allocate thread storage.\n");
1386 /* callid will be unreffed at thread destruction */
1387 ast_callid_ref(callid);
1389 #ifdef TEST_FRAMEWORK
1390 ast_debug(3, "CALL_ID [C-%08x] bound to thread.\n", callid->call_identifier);
1393 ast_log(LOG_WARNING, "Attempted to ast_callid_threadassoc_add on thread already associated with a callid.\n");
1400 int ast_callid_threadassoc_remove(void)
1402 struct ast_callid **pointing;
1403 pointing = ast_threadstorage_get(&unique_callid, sizeof(struct ast_callid **));
1405 ast_log(LOG_ERROR, "Failed to allocate thread storage.\n");
1410 ast_log(LOG_ERROR, "Tried to clean callid thread storage with no callid in thread storage.\n");
1413 #ifdef TEST_FRAMEWORK
1414 ast_debug(3, "CALL_ID [C-%08x] being removed from thread.\n", (*pointing)->call_identifier);
1416 *pointing = ast_callid_unref(*pointing);
1421 int ast_callid_threadstorage_auto(struct ast_callid **callid)
1423 struct ast_callid *tmp;
1425 /* Start by trying to see if a callid is available from thread storage */
1426 tmp = ast_read_threadstorage_callid();
1432 /* If that failed, try to create a new one and bind it. */
1433 tmp = ast_create_callid();
1435 ast_callid_threadassoc_add(tmp);
1440 /* If neither worked, then something must have gone wrong. */
1444 void ast_callid_threadstorage_auto_clean(struct ast_callid *callid, int callid_created)
1447 /* If the callid was created rather than simply grabbed from the thread storage, we need to unbind here. */
1448 if (callid_created == 1) {
1449 ast_callid_threadassoc_remove();
1451 callid = ast_callid_unref(callid);
1457 * \brief thread storage cleanup function for unique_callid
1459 static void unique_callid_cleanup(void *data)
1461 struct ast_callid **callid = data;
1464 ast_callid_unref(*callid);
1471 * \brief send log messages to syslog and/or the console
1473 static void __attribute__((format(printf, 6, 0))) ast_log_full(int level, const char *file, int line, const char *function, struct ast_callid *callid, const char *fmt, va_list ap)
1475 struct logmsg *logmsg = NULL;
1476 struct ast_str *buf = NULL;
1478 struct timeval now = ast_tvnow();
1480 char datestring[256];
1482 if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1485 if (level != __LOG_VERBOSE && AST_RWLIST_EMPTY(&logchannels)) {
1487 * we don't have the logger chain configured yet,
1488 * so just log to stdout
1491 result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1492 if (result != AST_DYNSTR_BUILD_FAILED) {
1493 term_filter_escapes(ast_str_buffer(buf));
1494 fputs(ast_str_buffer(buf), stdout);
1499 /* Ignore anything that never gets logged anywhere */
1500 if (level != __LOG_VERBOSE && !(global_logmask & (1 << level)))
1504 res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1506 /* If the build failed, then abort and free this structure */
1507 if (res == AST_DYNSTR_BUILD_FAILED)
1510 /* Create a new logging message */
1511 if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
1514 /* Copy string over */
1515 ast_string_field_set(logmsg, message, ast_str_buffer(buf));
1518 if (level == __LOG_VERBOSE) {
1519 logmsg->type = LOGMSG_VERBOSE;
1521 logmsg->type = LOGMSG_NORMAL;
1524 if (display_callids && callid) {
1525 logmsg->callid = ast_callid_ref(callid);
1526 /* callid will be unreffed at logmsg destruction */
1529 /* Create our date/time */
1530 ast_localtime(&now, &tm, NULL);
1531 ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
1532 ast_string_field_set(logmsg, date, datestring);
1534 /* Copy over data */
1535 logmsg->level = level;
1536 logmsg->line = line;
1537 ast_string_field_set(logmsg, level_name, levels[level]);
1538 ast_string_field_set(logmsg, file, file);
1539 ast_string_field_set(logmsg, function, function);
1540 logmsg->lwp = ast_get_tid();
1542 /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1543 if (logthread != AST_PTHREADT_NULL) {
1544 AST_LIST_LOCK(&logmsgs);
1545 if (close_logger_thread) {
1546 /* Logger is either closing or closed. We cannot log this message. */
1547 logmsg_free(logmsg);
1549 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1550 ast_cond_signal(&logcond);
1552 AST_LIST_UNLOCK(&logmsgs);
1554 logger_print_normal(logmsg);
1555 logmsg_free(logmsg);
1559 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
1561 struct ast_callid *callid;
1564 callid = ast_read_threadstorage_callid();
1567 ast_log_full(level, file, line, function, callid, fmt, ap);
1571 ast_callid_unref(callid);
1575 void ast_log_callid(int level, const char *file, int line, const char *function, struct ast_callid *callid, const char *fmt, ...)
1579 ast_log_full(level, file, line, function, callid, fmt, ap);
1585 struct ast_bt *ast_bt_create(void)
1587 struct ast_bt *bt = ast_calloc(1, sizeof(*bt));
1589 ast_log(LOG_ERROR, "Unable to allocate memory for backtrace structure!\n");
1595 ast_bt_get_addresses(bt);
1600 int ast_bt_get_addresses(struct ast_bt *bt)
1602 bt->num_frames = backtrace(bt->addresses, AST_MAX_BT_FRAMES);
1607 void *ast_bt_destroy(struct ast_bt *bt)
1616 char **ast_bt_get_symbols(void **addresses, size_t num_frames)
1618 char **strings = NULL;
1619 #if defined(BETTER_BACKTRACES)
1621 bfd *bfdobj; /* bfd.h */
1622 Dl_info dli; /* dlfcn.h */
1624 asymbol **syms = NULL; /* bfd.h */
1625 bfd_vma offset; /* bfd.h */
1626 const char *lastslash;
1628 const char *file, *func;
1630 char address_str[128];
1632 size_t strings_size;
1636 #if defined(BETTER_BACKTRACES)
1637 strings_size = num_frames * sizeof(*strings);
1638 eachlen = ast_calloc(num_frames, sizeof(*eachlen));
1640 if (!(strings = ast_calloc(num_frames, sizeof(*strings)))) {
1644 for (stackfr = 0; stackfr < num_frames; stackfr++) {
1645 int found = 0, symbolcount;
1649 if (!dladdr(addresses[stackfr], &dli)) {
1653 if (strcmp(dli.dli_fname, "asterisk") == 0) {
1654 char asteriskpath[256];
1655 if (!(dli.dli_fname = ast_utils_which("asterisk", asteriskpath, sizeof(asteriskpath)))) {
1656 /* This will fail to find symbols */
1657 ast_debug(1, "Failed to find asterisk binary for debug symbols.\n");
1658 dli.dli_fname = "asterisk";
1662 lastslash = strrchr(dli.dli_fname, '/');
1663 if ( (bfdobj = bfd_openr(dli.dli_fname, NULL)) &&
1664 bfd_check_format(bfdobj, bfd_object) &&
1665 (allocsize = bfd_get_symtab_upper_bound(bfdobj)) > 0 &&
1666 (syms = ast_malloc(allocsize)) &&
1667 (symbolcount = bfd_canonicalize_symtab(bfdobj, syms))) {
1669 if (bfdobj->flags & DYNAMIC) {
1670 offset = addresses[stackfr] - dli.dli_fbase;
1672 offset = addresses[stackfr] - (void *) 0;
1675 for (section = bfdobj->sections; section; section = section->next) {
1676 if ( !bfd_get_section_flags(bfdobj, section) & SEC_ALLOC ||
1677 section->vma > offset ||
1678 section->size + section->vma < offset) {
1682 if (!bfd_find_nearest_line(bfdobj, section, syms, offset - section->vma, &file, &func, &line)) {
1686 /* file can possibly be null even with a success result from bfd_find_nearest_line */
1687 file = file ? file : "";
1689 /* Stack trace output */
1691 if ((lastslash = strrchr(file, '/'))) {
1692 const char *prevslash;
1693 for (prevslash = lastslash - 1; *prevslash != '/' && prevslash >= file; prevslash--);
1694 if (prevslash >= file) {
1695 lastslash = prevslash;
1698 if (dli.dli_saddr == NULL) {
1699 address_str[0] = '\0';
1701 snprintf(address_str, sizeof(address_str), " (%p+%lX)",
1703 (unsigned long) (addresses[stackfr] - dli.dli_saddr));
1705 snprintf(msg, sizeof(msg), "%s:%u %s()%s",
1706 lastslash ? lastslash + 1 : file, line,
1710 break; /* out of section iteration */
1720 /* Default output, if we cannot find the information within BFD */
1722 if (dli.dli_saddr == NULL) {
1723 address_str[0] = '\0';
1725 snprintf(address_str, sizeof(address_str), " (%p+%lX)",
1727 (unsigned long) (addresses[stackfr] - dli.dli_saddr));
1729 snprintf(msg, sizeof(msg), "%s %s()%s",
1730 lastslash ? lastslash + 1 : dli.dli_fname,
1731 S_OR(dli.dli_sname, "<unknown>"),
1735 if (!ast_strlen_zero(msg)) {
1737 eachlen[stackfr] = strlen(msg);
1738 if (!(tmp = ast_realloc(strings, strings_size + eachlen[stackfr] + 1))) {
1741 break; /* out of stack frame iteration */
1744 strings[stackfr] = (char *) strings + strings_size;
1745 ast_copy_string(strings[stackfr], msg, eachlen[stackfr] + 1);
1746 strings_size += eachlen[stackfr] + 1;
1751 /* Recalculate the offset pointers */
1752 strings[0] = (char *) strings + num_frames * sizeof(*strings);
1753 for (stackfr = 1; stackfr < num_frames; stackfr++) {
1754 strings[stackfr] = strings[stackfr - 1] + eachlen[stackfr - 1] + 1;
1757 #else /* !defined(BETTER_BACKTRACES) */
1758 strings = backtrace_symbols(addresses, num_frames);
1759 #endif /* defined(BETTER_BACKTRACES) */
1763 #endif /* HAVE_BKTR */
1765 void ast_backtrace(void)
1772 if (!(bt = ast_bt_create())) {
1773 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
1777 if ((strings = ast_bt_get_symbols(bt->addresses, bt->num_frames))) {
1778 ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
1779 for (i = 3; i < bt->num_frames - 2; i++) {
1780 ast_debug(1, "#%d: [%p] %s\n", i - 3, bt->addresses[i], strings[i]);
1783 /* MALLOC_DEBUG will erroneously report an error here, unless we undef the macro. */
1787 ast_debug(1, "Could not allocate memory for backtrace\n");
1791 ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1792 #endif /* defined(HAVE_BKTR) */
1795 void __ast_verbose_ap(const char *file, int line, const char *func, int level, struct ast_callid *callid, const char *fmt, va_list ap)
1797 struct ast_str *buf = NULL;
1799 const char *prefix = level >= 4 ? VERBOSE_PREFIX_4 : level == 3 ? VERBOSE_PREFIX_3 : level == 2 ? VERBOSE_PREFIX_2 : level == 1 ? VERBOSE_PREFIX_1 : "";
1800 signed char magic = level > 127 ? -128 : -level - 1; /* 0 => -1, 1 => -2, etc. Can't pass NUL, as it is EOS-delimiter */
1802 /* For compatibility with modules still calling ast_verbose() directly instead of using ast_verb() */
1804 if (!strncmp(fmt, VERBOSE_PREFIX_4, strlen(VERBOSE_PREFIX_4))) {
1806 } else if (!strncmp(fmt, VERBOSE_PREFIX_3, strlen(VERBOSE_PREFIX_3))) {
1808 } else if (!strncmp(fmt, VERBOSE_PREFIX_2, strlen(VERBOSE_PREFIX_2))) {
1810 } else if (!strncmp(fmt, VERBOSE_PREFIX_1, strlen(VERBOSE_PREFIX_1))) {
1817 if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE))) {
1821 if (ast_opt_timestamp) {
1828 ast_localtime(&now, &tm, NULL);
1829 ast_strftime(date, sizeof(date), dateformat, &tm);
1830 datefmt = ast_alloca(strlen(date) + 3 + strlen(prefix) + strlen(fmt) + 1);
1831 sprintf(datefmt, "%c[%s] %s%s", (char) magic, date, prefix, fmt);
1834 char *tmp = ast_alloca(strlen(prefix) + strlen(fmt) + 2);
1835 sprintf(tmp, "%c%s%s", (char) magic, prefix, fmt);
1840 res = ast_str_set_va(&buf, 0, fmt, ap);
1842 /* If the build failed then we can drop this allocated message */
1843 if (res == AST_DYNSTR_BUILD_FAILED) {
1847 ast_log_callid(__LOG_VERBOSE, file, line, func, callid, "%s", ast_str_buffer(buf));
1850 void __ast_verbose(const char *file, int line, const char *func, int level, const char *fmt, ...)
1852 struct ast_callid *callid;
1855 callid = ast_read_threadstorage_callid();
1858 __ast_verbose_ap(file, line, func, level, callid, fmt, ap);
1862 ast_callid_unref(callid);
1866 void __ast_verbose_callid(const char *file, int line, const char *func, int level, struct ast_callid *callid, const char *fmt, ...)
1870 __ast_verbose_ap(file, line, func, level, callid, fmt, ap);
1874 /* No new code should use this directly, but we have the ABI for backwards compat */
1876 void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
1877 void ast_verbose(const char *fmt, ...)
1879 struct ast_callid *callid;
1882 callid = ast_read_threadstorage_callid();
1885 __ast_verbose_ap("", 0, "", 0, callid, fmt, ap);
1889 ast_callid_unref(callid);
1893 int ast_register_verbose(void (*v)(const char *string))
1897 if (!(verb = ast_malloc(sizeof(*verb))))
1902 AST_RWLIST_WRLOCK(&verbosers);
1903 AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1904 AST_RWLIST_UNLOCK(&verbosers);
1909 int ast_unregister_verbose(void (*v)(const char *string))
1913 AST_RWLIST_WRLOCK(&verbosers);
1914 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1915 if (cur->verboser == v) {
1916 AST_RWLIST_REMOVE_CURRENT(list);
1921 AST_RWLIST_TRAVERSE_SAFE_END;
1922 AST_RWLIST_UNLOCK(&verbosers);
1924 return cur ? 0 : -1;
1927 static void update_logchannels(void)
1929 struct logchannel *cur;
1931 AST_RWLIST_WRLOCK(&logchannels);
1935 AST_RWLIST_TRAVERSE(&logchannels, cur, list) {
1936 cur->logmask = make_components(cur->components, cur->lineno, &cur->verbosity);
1937 global_logmask |= cur->logmask;
1940 AST_RWLIST_UNLOCK(&logchannels);
1943 int ast_logger_register_level(const char *name)
1946 unsigned int available = 0;
1948 AST_RWLIST_WRLOCK(&logchannels);
1950 for (level = 0; level < ARRAY_LEN(levels); level++) {
1951 if ((level >= 16) && !available && !levels[level]) {
1956 if (levels[level] && !strcasecmp(levels[level], name)) {
1957 ast_log(LOG_WARNING,
1958 "Unable to register dynamic logger level '%s': a standard logger level uses that name.\n",
1960 AST_RWLIST_UNLOCK(&logchannels);
1967 ast_log(LOG_WARNING,
1968 "Unable to register dynamic logger level '%s'; maximum number of levels registered.\n",
1970 AST_RWLIST_UNLOCK(&logchannels);
1975 levels[available] = ast_strdup(name);
1977 AST_RWLIST_UNLOCK(&logchannels);
1979 ast_debug(1, "Registered dynamic logger level '%s' with index %d.\n", name, available);
1981 update_logchannels();
1986 void ast_logger_unregister_level(const char *name)
1988 unsigned int found = 0;
1991 AST_RWLIST_WRLOCK(&logchannels);
1993 for (x = 16; x < ARRAY_LEN(levels); x++) {
1998 if (strcasecmp(levels[x], name)) {
2007 /* take this level out of the global_logmask, to ensure that no new log messages
2008 * will be queued for it
2011 global_logmask &= ~(1 << x);
2013 ast_free(levels[x]);
2015 AST_RWLIST_UNLOCK(&logchannels);
2017 ast_debug(1, "Unregistered dynamic logger level '%s' with index %d.\n", name, x);
2019 update_logchannels();
2021 AST_RWLIST_UNLOCK(&logchannels);