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"
51 #include "asterisk/buildinfo.h"
52 #include "asterisk/ast_version.h"
60 #define MAX_BACKTRACE_FRAMES 20
61 # if defined(HAVE_DLADDR) && defined(HAVE_BFD) && defined(BETTER_BACKTRACES)
67 static char dateformat[256] = "%b %e %T"; /* Original Asterisk Format */
69 static char queue_log_name[256] = QUEUELOG;
70 static char exec_after_rotate[256] = "";
72 static int filesize_reload_needed;
73 static unsigned int global_logmask = 0xFFFF;
74 static int queuelog_init;
75 static int logger_initialized;
77 static enum rotatestrategy {
78 SEQUENTIAL = 1 << 0, /* Original method - create a new file, in order */
79 ROTATE = 1 << 1, /* Rotate all files, such that the oldest file has the highest suffix */
80 TIMESTAMP = 1 << 2, /* Append the epoch timestamp onto the end of the archived file */
81 } rotatestrategy = SEQUENTIAL;
84 unsigned int queue_log:1;
85 unsigned int queue_log_to_file:1;
86 unsigned int queue_adaptive_realtime:1;
89 static char hostname[MAXHOSTNAMELEN];
98 /*! What to log to this channel */
100 /*! If this channel is disabled or not */
102 /*! syslog facility */
104 /*! Verbosity level */
106 /*! Type of log channel */
108 /*! logfile logging file pointer */
111 char filename[PATH_MAX];
112 /*! field for linking to list */
113 AST_LIST_ENTRY(logchannel) list;
114 /*! Line number from configuration file */
116 /*! Components (levels) from last config load */
120 static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
128 enum logmsgtypes type;
132 AST_DECLARE_STRING_FIELDS(
133 AST_STRING_FIELD(date);
134 AST_STRING_FIELD(file);
135 AST_STRING_FIELD(function);
136 AST_STRING_FIELD(message);
137 AST_STRING_FIELD(level_name);
139 AST_LIST_ENTRY(logmsg) list;
142 static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
143 static pthread_t logthread = AST_PTHREADT_NULL;
144 static ast_cond_t logcond;
145 static int close_logger_thread = 0;
149 /*! \brief Logging channels used in the Asterisk logging system
151 * The first 16 levels are reserved for system usage, and the remaining
152 * levels are reserved for usage by dynamic levels registered via
153 * ast_logger_register_level.
156 /* Modifications to this array are protected by the rwlock in the
160 static char *levels[NUMLOGLEVELS] = {
162 "---EVENT---", /* no longer used */
170 /*! \brief Colors used in the console for logging */
171 static const int colors[NUMLOGLEVELS] = {
173 COLOR_BRBLUE, /* no longer used */
206 AST_THREADSTORAGE(verbose_buf);
207 #define VERBOSE_BUF_INIT_SIZE 256
209 AST_THREADSTORAGE(log_buf);
210 #define LOG_BUF_INIT_SIZE 256
212 static void logger_queue_init(void);
214 static unsigned int make_components(const char *s, int lineno, int *verbosity)
217 unsigned int res = 0;
218 char *stringp = ast_strdupa(s);
223 while ((w = strsep(&stringp, ","))) {
224 w = ast_skip_blanks(w);
226 if (!strcmp(w, "*")) {
229 } else if (!strncasecmp(w, "verbose(", 8) && sscanf(w + 8, "%d)", verbosity) == 1) {
230 res |= (1 << __LOG_VERBOSE);
232 } else for (x = 0; x < ARRAY_LEN(levels); x++) {
233 if (levels[x] && !strcasecmp(w, levels[x])) {
243 static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno)
245 struct logchannel *chan;
248 struct timeval now = ast_tvnow();
249 char datestring[256];
251 if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan) + strlen(components) + 1)))
254 strcpy(chan->components, components);
255 chan->lineno = lineno;
257 if (!strcasecmp(channel, "console")) {
258 chan->type = LOGTYPE_CONSOLE;
259 } else if (!strncasecmp(channel, "syslog", 6)) {
262 * syslog.facility => level,level,level
264 facility = strchr(channel, '.');
265 if (!facility++ || !facility) {
269 chan->facility = ast_syslog_facility(facility);
271 if (chan->facility < 0) {
272 fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
277 chan->type = LOGTYPE_SYSLOG;
278 ast_copy_string(chan->filename, channel, sizeof(chan->filename));
279 openlog("asterisk", LOG_PID, chan->facility);
281 if (!ast_strlen_zero(hostname)) {
282 snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s",
283 channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel, hostname);
285 snprintf(chan->filename, sizeof(chan->filename), "%s/%s",
286 channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel);
288 if (!(chan->fileptr = fopen(chan->filename, "a"))) {
289 /* Can't do real logging here since we're called with a lock
290 * so log to any attached consoles */
291 ast_console_puts_mutable("ERROR: Unable to open log file '", __LOG_ERROR);
292 ast_console_puts_mutable(chan->filename, __LOG_ERROR);
293 ast_console_puts_mutable("': ", __LOG_ERROR);
294 ast_console_puts_mutable(strerror(errno), __LOG_ERROR);
295 ast_console_puts_mutable("'\n", __LOG_ERROR);
299 /* Create our date/time */
300 ast_localtime(&now, &tm, NULL);
301 ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
303 fprintf(chan->fileptr, "[%s] Asterisk %s built by %s @ %s on a %s running %s on %s\n",
304 datestring, ast_get_version(), ast_build_user, ast_build_hostname,
305 ast_build_machine, ast_build_os, ast_build_date);
306 fflush(chan->fileptr);
308 chan->type = LOGTYPE_FILE;
310 chan->logmask = make_components(chan->components, lineno, &chan->verbosity);
315 static void init_logger_chain(int locked, const char *altconf)
317 struct logchannel *chan;
318 struct ast_config *cfg;
319 struct ast_variable *var;
321 struct ast_flags config_flags = { 0 };
323 if (!(cfg = ast_config_load2(S_OR(altconf, "logger.conf"), "logger", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID) {
327 /* delete our list of log channels */
329 AST_RWLIST_WRLOCK(&logchannels);
331 while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list))) {
336 AST_RWLIST_UNLOCK(&logchannels);
343 /* If no config file, we're fine, set default options. */
346 fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
348 fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
350 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
353 chan->type = LOGTYPE_CONSOLE;
354 chan->logmask = __LOG_WARNING | __LOG_NOTICE | __LOG_ERROR;
356 AST_RWLIST_WRLOCK(&logchannels);
358 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
359 global_logmask |= chan->logmask;
361 AST_RWLIST_UNLOCK(&logchannels);
366 if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
368 if (gethostname(hostname, sizeof(hostname) - 1)) {
369 ast_copy_string(hostname, "unknown", sizeof(hostname));
370 fprintf(stderr, "What box has no hostname???\n");
376 if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
377 ast_copy_string(dateformat, s, sizeof(dateformat));
379 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
380 if ((s = ast_variable_retrieve(cfg, "general", "queue_log"))) {
381 logfiles.queue_log = ast_true(s);
383 if ((s = ast_variable_retrieve(cfg, "general", "queue_log_to_file"))) {
384 logfiles.queue_log_to_file = ast_true(s);
386 if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name"))) {
387 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));
392 if ((s = ast_variable_retrieve(cfg, "general", "rotatestrategy"))) {
393 if (strcasecmp(s, "timestamp") == 0) {
394 rotatestrategy = TIMESTAMP;
395 } else if (strcasecmp(s, "rotate") == 0) {
396 rotatestrategy = ROTATE;
397 } else if (strcasecmp(s, "sequential") == 0) {
398 rotatestrategy = SEQUENTIAL;
400 fprintf(stderr, "Unknown rotatestrategy: %s\n", s);
403 if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp"))) {
404 rotatestrategy = ast_true(s) ? TIMESTAMP : SEQUENTIAL;
405 fprintf(stderr, "rotatetimestamp option has been deprecated. Please use rotatestrategy instead.\n");
410 AST_RWLIST_WRLOCK(&logchannels);
412 var = ast_variable_browse(cfg, "logfiles");
413 for (; var; var = var->next) {
414 if (!(chan = make_logchannel(var->name, var->value, var->lineno))) {
415 /* Print error message directly to the consoles since the lock is held
416 * and we don't want to unlock with the list partially built */
417 ast_console_puts_mutable("ERROR: Unable to create log channel '", __LOG_ERROR);
418 ast_console_puts_mutable(var->name, __LOG_ERROR);
419 ast_console_puts_mutable("'\n", __LOG_ERROR);
422 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
423 global_logmask |= chan->logmask;
432 AST_RWLIST_UNLOCK(&logchannels);
435 ast_config_destroy(cfg);
438 void ast_child_verbose(int level, const char *fmt, ...)
440 char *msg = NULL, *emsg = NULL, *sptr, *eptr;
446 if ((size = vsnprintf(msg, 0, fmt, ap)) < 0) {
453 if (!(msg = ast_malloc(size + 1))) {
458 vsnprintf(msg, size + 1, fmt, aq);
461 if (!(emsg = ast_malloc(size * 2 + 1))) {
466 for (sptr = msg, eptr = emsg; ; sptr++) {
477 fprintf(stdout, "verbose \"%s\" %d\n", emsg, level);
482 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
491 if (!logger_initialized) {
492 /* You are too early. We are not open yet! */
495 if (!queuelog_init) {
496 AST_RWLIST_WRLOCK(&logchannels);
497 if (!queuelog_init) {
499 * We have delayed initializing the queue logging system so
500 * preloaded realtime modules can get up. We must initialize
501 * now since someone is trying to log something.
505 AST_RWLIST_UNLOCK(&logchannels);
506 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
508 AST_RWLIST_UNLOCK(&logchannels);
512 if (ast_check_realtime("queue_log")) {
514 ast_localtime(&tv, &tm, NULL);
515 ast_strftime(time_str, sizeof(time_str), "%F %T.%6q", &tm);
517 vsnprintf(qlog_msg, sizeof(qlog_msg), fmt, ap);
519 if (logfiles.queue_adaptive_realtime) {
520 AST_DECLARE_APP_ARGS(args,
521 AST_APP_ARG(data)[5];
523 AST_NONSTANDARD_APP_ARGS(args, qlog_msg, '|');
524 /* Ensure fields are large enough to receive data */
525 ast_realtime_require_field("queue_log",
526 "data1", RQ_CHAR, strlen(S_OR(args.data[0], "")),
527 "data2", RQ_CHAR, strlen(S_OR(args.data[1], "")),
528 "data3", RQ_CHAR, strlen(S_OR(args.data[2], "")),
529 "data4", RQ_CHAR, strlen(S_OR(args.data[3], "")),
530 "data5", RQ_CHAR, strlen(S_OR(args.data[4], "")),
534 ast_store_realtime("queue_log", "time", time_str,
536 "queuename", queuename,
539 "data1", S_OR(args.data[0], ""),
540 "data2", S_OR(args.data[1], ""),
541 "data3", S_OR(args.data[2], ""),
542 "data4", S_OR(args.data[3], ""),
543 "data5", S_OR(args.data[4], ""),
546 ast_store_realtime("queue_log", "time", time_str,
548 "queuename", queuename,
555 if (!logfiles.queue_log_to_file) {
562 qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
563 vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
565 AST_RWLIST_RDLOCK(&logchannels);
567 fprintf(qlog, "%s\n", qlog_msg);
570 AST_RWLIST_UNLOCK(&logchannels);
574 static int rotate_file(const char *filename)
578 int x, y, which, found, res = 0, fd;
579 char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
581 switch (rotatestrategy) {
584 snprintf(new, sizeof(new), "%s.%d", filename, x);
585 fd = open(new, O_RDONLY);
591 if (rename(filename, new)) {
592 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
599 snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
600 if (rename(filename, new)) {
601 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
608 /* Find the next empty slot, including a possible suffix */
611 for (which = 0; which < ARRAY_LEN(suffixes); which++) {
612 snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
613 fd = open(new, O_RDONLY);
625 /* Found an empty slot */
626 for (y = x; y > 0; y--) {
627 for (which = 0; which < ARRAY_LEN(suffixes); which++) {
628 snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
629 fd = open(old, O_RDONLY);
631 /* Found the right suffix */
633 snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
634 if (rename(old, new)) {
635 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
643 /* Finally, rename the current file */
644 snprintf(new, sizeof(new), "%s.0", filename);
645 if (rename(filename, new)) {
646 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
653 if (!ast_strlen_zero(exec_after_rotate)) {
654 struct ast_channel *c = ast_dummy_channel_alloc();
657 pbx_builtin_setvar_helper(c, "filename", filename);
658 pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
660 c = ast_channel_unref(c);
662 if (ast_safe_system(buf) == -1) {
663 ast_log(LOG_WARNING, "error executing '%s'\n", buf);
671 * \brief Start the realtime queue logging if configured.
673 * \retval TRUE if not to open queue log file.
675 static int logger_queue_rt_start(void)
677 if (ast_check_realtime("queue_log")) {
678 if (!ast_realtime_require_field("queue_log",
679 "time", RQ_DATETIME, 26,
680 "data1", RQ_CHAR, 20,
681 "data2", RQ_CHAR, 20,
682 "data3", RQ_CHAR, 20,
683 "data4", RQ_CHAR, 20,
684 "data5", RQ_CHAR, 20,
686 logfiles.queue_adaptive_realtime = 1;
688 logfiles.queue_adaptive_realtime = 0;
691 if (!logfiles.queue_log_to_file) {
692 /* Don't open the log file. */
701 * \brief Rotate the queue log file and restart.
703 * \param queue_rotate Log queue rotation mode.
705 * \note Assumes logchannels is write locked on entry.
707 * \retval 0 on success.
708 * \retval -1 on error.
710 static int logger_queue_restart(int queue_rotate)
713 char qfname[PATH_MAX];
715 if (logger_queue_rt_start()) {
719 snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
721 /* Just in case it was still open. */
729 /* Open the log file. */
730 qlog = fopen(qfname, "a");
732 ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
738 static int reload_logger(int rotate, const char *altconf)
740 int queue_rotate = rotate;
741 struct logchannel *f;
744 AST_RWLIST_WRLOCK(&logchannels);
748 /* Check filesize - this one typically doesn't need an auto-rotate */
749 if (ftello(qlog) > 0x40000000) { /* Arbitrarily, 1 GB */
763 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
765 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
767 f->disabled = 0; /* Re-enable logging at reload */
768 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
770 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
772 if (ftello(f->fileptr) > 0x40000000) { /* Arbitrarily, 1 GB */
773 /* Be more proactive about rotating massive log files */
776 fclose(f->fileptr); /* Close file */
778 if (rotate || rotate_this) {
779 rotate_file(f->filename);
784 filesize_reload_needed = 0;
786 init_logger_chain(1 /* locked */, altconf);
788 ast_unload_realtime("queue_log");
789 if (logfiles.queue_log) {
790 res = logger_queue_restart(queue_rotate);
791 AST_RWLIST_UNLOCK(&logchannels);
792 ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
793 ast_verb(1, "Asterisk Queue Logger restarted\n");
795 AST_RWLIST_UNLOCK(&logchannels);
801 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
802 a full Asterisk reload) */
803 int logger_reload(void)
805 if (reload_logger(0, NULL)) {
806 return RESULT_FAILURE;
808 return RESULT_SUCCESS;
811 static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
815 e->command = "logger reload";
817 "Usage: logger reload [<alt-conf>]\n"
818 " Reloads the logger subsystem state. Use after restarting syslogd(8) if you are using syslog logging.\n";
823 if (reload_logger(0, a->argc == 3 ? a->argv[2] : NULL)) {
824 ast_cli(a->fd, "Failed to reload the logger\n");
830 static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
834 e->command = "logger rotate";
836 "Usage: logger rotate\n"
837 " Rotates and Reopens the log files.\n";
842 if (reload_logger(1, NULL)) {
843 ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
849 static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
857 e->command = "logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}";
859 "Usage: logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}\n"
860 " Set a specific log level to enabled/disabled for this console.\n";
867 return CLI_SHOWUSAGE;
869 AST_RWLIST_WRLOCK(&logchannels);
871 for (x = 0; x < ARRAY_LEN(levels); x++) {
872 if (levels[x] && !strcasecmp(a->argv[3], levels[x])) {
878 AST_RWLIST_UNLOCK(&logchannels);
880 state = ast_true(a->argv[4]) ? 1 : 0;
883 ast_console_toggle_loglevel(a->fd, level, state);
884 ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
886 return CLI_SHOWUSAGE;
891 /*! \brief CLI command to show logging system configuration */
892 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
894 #define FORMATL "%-35.35s %-8.8s %-9.9s "
895 struct logchannel *chan;
898 e->command = "logger show channels";
900 "Usage: logger show channels\n"
901 " List configured logger channels.\n";
906 ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
907 ast_cli(a->fd, "Configuration\n");
908 ast_cli(a->fd, FORMATL, "-------", "----", "------");
909 ast_cli(a->fd, "-------------\n");
910 AST_RWLIST_RDLOCK(&logchannels);
911 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
914 ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
915 chan->disabled ? "Disabled" : "Enabled");
916 ast_cli(a->fd, " - ");
917 for (level = 0; level < ARRAY_LEN(levels); level++) {
918 if ((chan->logmask & (1 << level)) && levels[level]) {
919 ast_cli(a->fd, "%s ", levels[level]);
922 ast_cli(a->fd, "\n");
924 AST_RWLIST_UNLOCK(&logchannels);
925 ast_cli(a->fd, "\n");
931 void (*verboser)(const char *string);
932 AST_LIST_ENTRY(verb) list;
935 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
937 static struct ast_cli_entry cli_logger[] = {
938 AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
939 AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
940 AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
941 AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console")
944 static void _handle_SIGXFSZ(int sig)
946 /* Indicate need to reload */
947 filesize_reload_needed = 1;
950 static struct sigaction handle_SIGXFSZ = {
951 .sa_handler = _handle_SIGXFSZ,
952 .sa_flags = SA_RESTART,
955 static void ast_log_vsyslog(struct logmsg *msg)
958 int syslog_level = ast_syslog_priority_from_loglevel(msg->level);
960 if (syslog_level < 0) {
961 /* we are locked here, so cannot ast_log() */
962 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", msg->level);
966 snprintf(buf, sizeof(buf), "%s[%d]: %s:%d in %s: %s",
967 levels[msg->level], msg->lwp, msg->file, msg->line, msg->function, msg->message);
969 term_strip(buf, buf, strlen(buf) + 1);
970 syslog(syslog_level, "%s", buf);
973 /* These gymnastics are due to platforms which designate char as unsigned by
974 * default. Level is the negative character -- offset by 1, because \0 is the
976 #define VERBOSE_MAGIC2LEVEL(x) (((char) -*(signed char *) (x)) - 1)
977 #define VERBOSE_HASMAGIC(x) (*(signed char *) (x) < 0)
979 /*! \brief Print a normal log message to the channels */
980 static void logger_print_normal(struct logmsg *logmsg)
982 struct logchannel *chan = NULL;
984 struct verb *v = NULL;
987 if (logmsg->level == __LOG_VERBOSE) {
988 char *tmpmsg = ast_strdupa(logmsg->message + 1);
989 level = VERBOSE_MAGIC2LEVEL(logmsg->message);
990 /* Iterate through the list of verbosers and pass them the log message string */
991 AST_RWLIST_RDLOCK(&verbosers);
992 AST_RWLIST_TRAVERSE(&verbosers, v, list)
993 v->verboser(logmsg->message);
994 AST_RWLIST_UNLOCK(&verbosers);
995 ast_string_field_set(logmsg, message, tmpmsg);
998 AST_RWLIST_RDLOCK(&logchannels);
1000 if (!AST_RWLIST_EMPTY(&logchannels)) {
1001 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
1002 /* If the channel is disabled, then move on to the next one */
1003 if (chan->disabled) {
1006 if (logmsg->level == __LOG_VERBOSE && level > chan->verbosity) {
1010 /* Check syslog channels */
1011 if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
1012 ast_log_vsyslog(logmsg);
1013 /* Console channels */
1014 } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
1016 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
1018 /* If the level is verbose, then skip it */
1019 if (logmsg->level == __LOG_VERBOSE)
1022 /* Turn the numerical line number into a string */
1023 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
1024 /* Build string to print out */
1025 snprintf(buf, sizeof(buf), "[%s] %s[%d]: %s:%s %s: %s",
1027 term_color(tmp1, logmsg->level_name, colors[logmsg->level], 0, sizeof(tmp1)),
1029 term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
1030 term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
1031 term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
1034 ast_console_puts_mutable(buf, logmsg->level);
1036 } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
1039 /* If no file pointer exists, skip it */
1040 if (!chan->fileptr) {
1044 /* Print out to the file */
1045 res = fprintf(chan->fileptr, "[%s] %s[%d] %s: %s",
1046 logmsg->date, logmsg->level_name, logmsg->lwp, logmsg->file, term_strip(buf, logmsg->message, BUFSIZ));
1047 if (res <= 0 && !ast_strlen_zero(logmsg->message)) {
1048 fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
1049 if (errno == ENOMEM || errno == ENOSPC)
1050 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
1052 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
1053 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
1055 } else if (res > 0) {
1056 fflush(chan->fileptr);
1060 } else if (logmsg->level != __LOG_VERBOSE) {
1061 fputs(logmsg->message, stdout);
1064 AST_RWLIST_UNLOCK(&logchannels);
1066 /* If we need to reload because of the file size, then do so */
1067 if (filesize_reload_needed) {
1068 reload_logger(-1, NULL);
1069 ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
1075 /*! \brief Actual logging thread */
1076 static void *logger_thread(void *data)
1078 struct logmsg *next = NULL, *msg = NULL;
1081 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
1082 AST_LIST_LOCK(&logmsgs);
1083 if (AST_LIST_EMPTY(&logmsgs)) {
1084 if (close_logger_thread) {
1087 ast_cond_wait(&logcond, &logmsgs.lock);
1090 next = AST_LIST_FIRST(&logmsgs);
1091 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
1092 AST_LIST_UNLOCK(&logmsgs);
1094 /* Otherwise go through and process each message in the order added */
1095 while ((msg = next)) {
1096 /* Get the next entry now so that we can free our current structure later */
1097 next = AST_LIST_NEXT(msg, list);
1099 /* Depending on the type, send it to the proper function */
1100 logger_print_normal(msg);
1102 /* Free the data since we are done */
1106 /* If we should stop, then stop */
1107 if (close_logger_thread)
1116 * \brief Initialize the logger queue.
1118 * \note Assumes logchannels is write locked on entry.
1122 static void logger_queue_init(void)
1124 ast_unload_realtime("queue_log");
1125 if (logfiles.queue_log) {
1126 char qfname[PATH_MAX];
1128 if (logger_queue_rt_start()) {
1132 /* Open the log file. */
1133 snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR,
1136 /* Just in case it was already open. */
1139 qlog = fopen(qfname, "a");
1141 ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
1146 int init_logger(void)
1148 /* auto rotate if sig SIGXFSZ comes a-knockin */
1149 sigaction(SIGXFSZ, &handle_SIGXFSZ, NULL);
1151 /* start logger thread */
1152 ast_cond_init(&logcond, NULL);
1153 if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
1154 ast_cond_destroy(&logcond);
1158 /* register the logger cli commands */
1159 ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
1161 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
1163 /* create log channels */
1164 init_logger_chain(0 /* locked */, NULL);
1165 logger_initialized = 1;
1170 void close_logger(void)
1172 struct logchannel *f = NULL;
1174 logger_initialized = 0;
1176 /* Stop logger thread */
1177 AST_LIST_LOCK(&logmsgs);
1178 close_logger_thread = 1;
1179 ast_cond_signal(&logcond);
1180 AST_LIST_UNLOCK(&logmsgs);
1182 if (logthread != AST_PTHREADT_NULL)
1183 pthread_join(logthread, NULL);
1185 AST_RWLIST_WRLOCK(&logchannels);
1192 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
1193 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
1199 closelog(); /* syslog */
1201 AST_RWLIST_UNLOCK(&logchannels);
1207 * \brief send log messages to syslog and/or the console
1209 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
1211 struct logmsg *logmsg = NULL;
1212 struct ast_str *buf = NULL;
1214 struct timeval now = ast_tvnow();
1217 char datestring[256];
1219 if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1222 if (level != __LOG_VERBOSE && AST_RWLIST_EMPTY(&logchannels)) {
1224 * we don't have the logger chain configured yet,
1225 * so just log to stdout
1229 result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1231 if (result != AST_DYNSTR_BUILD_FAILED) {
1232 term_filter_escapes(ast_str_buffer(buf));
1233 fputs(ast_str_buffer(buf), stdout);
1238 /* Ignore anything that never gets logged anywhere */
1239 if (level != __LOG_VERBOSE && !(global_logmask & (1 << level)))
1244 res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1247 /* If the build failed, then abort and free this structure */
1248 if (res == AST_DYNSTR_BUILD_FAILED)
1251 /* Create a new logging message */
1252 if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
1255 /* Copy string over */
1256 ast_string_field_set(logmsg, message, ast_str_buffer(buf));
1259 if (level == __LOG_VERBOSE) {
1260 logmsg->type = LOGMSG_VERBOSE;
1262 logmsg->type = LOGMSG_NORMAL;
1265 /* Create our date/time */
1266 ast_localtime(&now, &tm, NULL);
1267 ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
1268 ast_string_field_set(logmsg, date, datestring);
1270 /* Copy over data */
1271 logmsg->level = level;
1272 logmsg->line = line;
1273 ast_string_field_set(logmsg, level_name, levels[level]);
1274 ast_string_field_set(logmsg, file, file);
1275 ast_string_field_set(logmsg, function, function);
1276 logmsg->lwp = ast_get_tid();
1278 /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1279 if (logthread != AST_PTHREADT_NULL) {
1280 AST_LIST_LOCK(&logmsgs);
1281 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1282 ast_cond_signal(&logcond);
1283 AST_LIST_UNLOCK(&logmsgs);
1285 logger_print_normal(logmsg);
1294 struct ast_bt *ast_bt_create(void)
1296 struct ast_bt *bt = ast_calloc(1, sizeof(*bt));
1298 ast_log(LOG_ERROR, "Unable to allocate memory for backtrace structure!\n");
1304 ast_bt_get_addresses(bt);
1309 int ast_bt_get_addresses(struct ast_bt *bt)
1311 bt->num_frames = backtrace(bt->addresses, AST_MAX_BT_FRAMES);
1316 void *ast_bt_destroy(struct ast_bt *bt)
1325 char **ast_bt_get_symbols(void **addresses, size_t num_frames)
1327 char **strings = NULL;
1328 #if defined(BETTER_BACKTRACES)
1330 bfd *bfdobj; /* bfd.h */
1331 Dl_info dli; /* dlfcn.h */
1333 asymbol **syms = NULL; /* bfd.h */
1334 bfd_vma offset; /* bfd.h */
1335 const char *lastslash;
1337 const char *file, *func;
1339 char address_str[128];
1341 size_t strings_size;
1345 #if defined(BETTER_BACKTRACES)
1346 strings_size = num_frames * sizeof(*strings);
1347 eachlen = ast_calloc(num_frames, sizeof(*eachlen));
1349 if (!(strings = ast_calloc(num_frames, sizeof(*strings)))) {
1353 for (stackfr = 0; stackfr < num_frames; stackfr++) {
1354 int found = 0, symbolcount;
1358 if (!dladdr(addresses[stackfr], &dli)) {
1362 if (strcmp(dli.dli_fname, "asterisk") == 0) {
1363 char asteriskpath[256];
1364 if (!(dli.dli_fname = ast_utils_which("asterisk", asteriskpath, sizeof(asteriskpath)))) {
1365 /* This will fail to find symbols */
1366 ast_debug(1, "Failed to find asterisk binary for debug symbols.\n");
1367 dli.dli_fname = "asterisk";
1371 lastslash = strrchr(dli.dli_fname, '/');
1372 if ( (bfdobj = bfd_openr(dli.dli_fname, NULL)) &&
1373 bfd_check_format(bfdobj, bfd_object) &&
1374 (allocsize = bfd_get_symtab_upper_bound(bfdobj)) > 0 &&
1375 (syms = ast_malloc(allocsize)) &&
1376 (symbolcount = bfd_canonicalize_symtab(bfdobj, syms))) {
1378 if (bfdobj->flags & DYNAMIC) {
1379 offset = addresses[stackfr] - dli.dli_fbase;
1381 offset = addresses[stackfr] - (void *) 0;
1384 for (section = bfdobj->sections; section; section = section->next) {
1385 if ( !bfd_get_section_flags(bfdobj, section) & SEC_ALLOC ||
1386 section->vma > offset ||
1387 section->size + section->vma < offset) {
1391 if (!bfd_find_nearest_line(bfdobj, section, syms, offset - section->vma, &file, &func, &line)) {
1395 /* Stack trace output */
1397 if ((lastslash = strrchr(file, '/'))) {
1398 const char *prevslash;
1399 for (prevslash = lastslash - 1; *prevslash != '/' && prevslash >= file; prevslash--);
1400 if (prevslash >= file) {
1401 lastslash = prevslash;
1404 if (dli.dli_saddr == NULL) {
1405 address_str[0] = '\0';
1407 snprintf(address_str, sizeof(address_str), " (%p+%lX)",
1409 (unsigned long) (addresses[stackfr] - dli.dli_saddr));
1411 snprintf(msg, sizeof(msg), "%s:%u %s()%s",
1412 lastslash ? lastslash + 1 : file, line,
1416 break; /* out of section iteration */
1426 /* Default output, if we cannot find the information within BFD */
1428 if (dli.dli_saddr == NULL) {
1429 address_str[0] = '\0';
1431 snprintf(address_str, sizeof(address_str), " (%p+%lX)",
1433 (unsigned long) (addresses[stackfr] - dli.dli_saddr));
1435 snprintf(msg, sizeof(msg), "%s %s()%s",
1436 lastslash ? lastslash + 1 : dli.dli_fname,
1437 S_OR(dli.dli_sname, "<unknown>"),
1441 if (!ast_strlen_zero(msg)) {
1443 eachlen[stackfr] = strlen(msg);
1444 if (!(tmp = ast_realloc(strings, strings_size + eachlen[stackfr] + 1))) {
1447 break; /* out of stack frame iteration */
1450 strings[stackfr] = (char *) strings + strings_size;
1451 ast_copy_string(strings[stackfr], msg, eachlen[stackfr] + 1);
1452 strings_size += eachlen[stackfr] + 1;
1457 /* Recalculate the offset pointers */
1458 strings[0] = (char *) strings + num_frames * sizeof(*strings);
1459 for (stackfr = 1; stackfr < num_frames; stackfr++) {
1460 strings[stackfr] = strings[stackfr - 1] + eachlen[stackfr - 1] + 1;
1463 #else /* !defined(BETTER_BACKTRACES) */
1464 strings = backtrace_symbols(addresses, num_frames);
1465 #endif /* defined(BETTER_BACKTRACES) */
1469 #endif /* HAVE_BKTR */
1471 void ast_backtrace(void)
1478 if (!(bt = ast_bt_create())) {
1479 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
1483 if ((strings = ast_bt_get_symbols(bt->addresses, bt->num_frames))) {
1484 ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
1485 for (i = 3; i < bt->num_frames - 2; i++) {
1486 ast_debug(1, "#%d: [%p] %s\n", i - 3, bt->addresses[i], strings[i]);
1489 /* MALLOC_DEBUG will erroneously report an error here, unless we undef the macro. */
1493 ast_debug(1, "Could not allocate memory for backtrace\n");
1497 ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1498 #endif /* defined(HAVE_BKTR) */
1501 void __ast_verbose_ap(const char *file, int line, const char *func, int level, const char *fmt, va_list ap)
1503 struct ast_str *buf = NULL;
1505 const char *prefix = level >= 4 ? VERBOSE_PREFIX_4 : level == 3 ? VERBOSE_PREFIX_3 : level == 2 ? VERBOSE_PREFIX_2 : level == 1 ? VERBOSE_PREFIX_1 : "";
1506 signed char magic = level > 127 ? -128 : -level - 1; /* 0 => -1, 1 => -2, etc. Can't pass NUL, as it is EOS-delimiter */
1508 /* For compatibility with modules still calling ast_verbose() directly instead of using ast_verb() */
1510 if (!strncmp(fmt, VERBOSE_PREFIX_4, strlen(VERBOSE_PREFIX_4))) {
1512 } else if (!strncmp(fmt, VERBOSE_PREFIX_3, strlen(VERBOSE_PREFIX_3))) {
1514 } else if (!strncmp(fmt, VERBOSE_PREFIX_2, strlen(VERBOSE_PREFIX_2))) {
1516 } else if (!strncmp(fmt, VERBOSE_PREFIX_1, strlen(VERBOSE_PREFIX_1))) {
1523 if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE))) {
1527 if (ast_opt_timestamp) {
1534 ast_localtime(&now, &tm, NULL);
1535 ast_strftime(date, sizeof(date), dateformat, &tm);
1536 datefmt = alloca(strlen(date) + 3 + strlen(prefix) + strlen(fmt) + 1);
1537 sprintf(datefmt, "%c[%s] %s%s", (char) magic, date, prefix, fmt);
1540 char *tmp = alloca(strlen(prefix) + strlen(fmt) + 2);
1541 sprintf(tmp, "%c%s%s", (char) magic, prefix, fmt);
1546 res = ast_str_set_va(&buf, 0, fmt, ap);
1548 /* If the build failed then we can drop this allocated message */
1549 if (res == AST_DYNSTR_BUILD_FAILED) {
1553 ast_log(__LOG_VERBOSE, file, line, func, "%s", ast_str_buffer(buf));
1556 void __ast_verbose(const char *file, int line, const char *func, int level, const char *fmt, ...)
1561 __ast_verbose_ap(file, line, func, level, fmt, ap);
1565 /* No new code should use this directly, but we have the ABI for backwards compat */
1567 void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
1568 void ast_verbose(const char *fmt, ...)
1573 __ast_verbose_ap("", 0, "", 0, fmt, ap);
1577 int ast_register_verbose(void (*v)(const char *string))
1581 if (!(verb = ast_malloc(sizeof(*verb))))
1586 AST_RWLIST_WRLOCK(&verbosers);
1587 AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1588 AST_RWLIST_UNLOCK(&verbosers);
1593 int ast_unregister_verbose(void (*v)(const char *string))
1597 AST_RWLIST_WRLOCK(&verbosers);
1598 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1599 if (cur->verboser == v) {
1600 AST_RWLIST_REMOVE_CURRENT(list);
1605 AST_RWLIST_TRAVERSE_SAFE_END;
1606 AST_RWLIST_UNLOCK(&verbosers);
1608 return cur ? 0 : -1;
1611 static void update_logchannels(void)
1613 struct logchannel *cur;
1615 AST_RWLIST_WRLOCK(&logchannels);
1619 AST_RWLIST_TRAVERSE(&logchannels, cur, list) {
1620 cur->logmask = make_components(cur->components, cur->lineno, &cur->verbosity);
1621 global_logmask |= cur->logmask;
1624 AST_RWLIST_UNLOCK(&logchannels);
1627 int ast_logger_register_level(const char *name)
1630 unsigned int available = 0;
1632 AST_RWLIST_WRLOCK(&logchannels);
1634 for (level = 0; level < ARRAY_LEN(levels); level++) {
1635 if ((level >= 16) && !available && !levels[level]) {
1640 if (levels[level] && !strcasecmp(levels[level], name)) {
1641 ast_log(LOG_WARNING,
1642 "Unable to register dynamic logger level '%s': a standard logger level uses that name.\n",
1644 AST_RWLIST_UNLOCK(&logchannels);
1651 ast_log(LOG_WARNING,
1652 "Unable to register dynamic logger level '%s'; maximum number of levels registered.\n",
1654 AST_RWLIST_UNLOCK(&logchannels);
1659 levels[available] = ast_strdup(name);
1661 AST_RWLIST_UNLOCK(&logchannels);
1663 ast_debug(1, "Registered dynamic logger level '%s' with index %d.\n", name, available);
1665 update_logchannels();
1670 void ast_logger_unregister_level(const char *name)
1672 unsigned int found = 0;
1675 AST_RWLIST_WRLOCK(&logchannels);
1677 for (x = 16; x < ARRAY_LEN(levels); x++) {
1682 if (strcasecmp(levels[x], name)) {
1691 /* take this level out of the global_logmask, to ensure that no new log messages
1692 * will be queued for it
1695 global_logmask &= ~(1 << x);
1697 ast_free(levels[x]);
1699 AST_RWLIST_UNLOCK(&logchannels);
1701 ast_debug(1, "Unregistered dynamic logger level '%s' with index %d.\n", name, x);
1703 update_logchannels();
1705 AST_RWLIST_UNLOCK(&logchannels);