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 /*! Type of log channel */
106 /*! logfile logging file pointer */
109 char filename[PATH_MAX];
110 /*! field for linking to list */
111 AST_LIST_ENTRY(logchannel) list;
112 /*! Line number from configuration file */
114 /*! Components (levels) from last config load */
118 static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
126 enum logmsgtypes type;
130 AST_DECLARE_STRING_FIELDS(
131 AST_STRING_FIELD(date);
132 AST_STRING_FIELD(file);
133 AST_STRING_FIELD(function);
134 AST_STRING_FIELD(message);
135 AST_STRING_FIELD(level_name);
137 AST_LIST_ENTRY(logmsg) list;
140 static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
141 static pthread_t logthread = AST_PTHREADT_NULL;
142 static ast_cond_t logcond;
143 static int close_logger_thread = 0;
147 /*! \brief Logging channels used in the Asterisk logging system
149 * The first 16 levels are reserved for system usage, and the remaining
150 * levels are reserved for usage by dynamic levels registered via
151 * ast_logger_register_level.
154 /* Modifications to this array are protected by the rwlock in the
158 static char *levels[32] = {
160 "---EVENT---", /* no longer used */
168 /*! \brief Colors used in the console for logging */
169 static const int colors[32] = {
171 COLOR_BRBLUE, /* no longer used */
204 AST_THREADSTORAGE(verbose_buf);
205 #define VERBOSE_BUF_INIT_SIZE 256
207 AST_THREADSTORAGE(log_buf);
208 #define LOG_BUF_INIT_SIZE 256
210 static void logger_queue_init(void);
212 static unsigned int make_components(const char *s, int lineno)
215 unsigned int res = 0;
216 char *stringp = ast_strdupa(s);
219 while ((w = strsep(&stringp, ","))) {
220 w = ast_skip_blanks(w);
222 if (!strcmp(w, "*")) {
225 } else for (x = 0; x < ARRAY_LEN(levels); x++) {
226 if (levels[x] && !strcasecmp(w, levels[x])) {
236 static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno)
238 struct logchannel *chan;
241 struct timeval now = ast_tvnow();
242 char datestring[256];
244 if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan) + strlen(components) + 1)))
247 strcpy(chan->components, components);
248 chan->lineno = lineno;
250 if (!strcasecmp(channel, "console")) {
251 chan->type = LOGTYPE_CONSOLE;
252 } else if (!strncasecmp(channel, "syslog", 6)) {
255 * syslog.facility => level,level,level
257 facility = strchr(channel, '.');
258 if (!facility++ || !facility) {
262 chan->facility = ast_syslog_facility(facility);
264 if (chan->facility < 0) {
265 fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
270 chan->type = LOGTYPE_SYSLOG;
271 ast_copy_string(chan->filename, channel, sizeof(chan->filename));
272 openlog("asterisk", LOG_PID, chan->facility);
274 if (!ast_strlen_zero(hostname)) {
275 snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s",
276 channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel, hostname);
278 snprintf(chan->filename, sizeof(chan->filename), "%s/%s",
279 channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel);
281 if (!(chan->fileptr = fopen(chan->filename, "a"))) {
282 /* Can't do real logging here since we're called with a lock
283 * so log to any attached consoles */
284 ast_console_puts_mutable("ERROR: Unable to open log file '", __LOG_ERROR);
285 ast_console_puts_mutable(chan->filename, __LOG_ERROR);
286 ast_console_puts_mutable("': ", __LOG_ERROR);
287 ast_console_puts_mutable(strerror(errno), __LOG_ERROR);
288 ast_console_puts_mutable("'\n", __LOG_ERROR);
292 /* Create our date/time */
293 ast_localtime(&now, &tm, NULL);
294 ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
296 fprintf(chan->fileptr, "[%s] Asterisk %s built by %s @ %s on a %s running %s on %s\n",
297 datestring, ast_get_version(), ast_build_user, ast_build_hostname,
298 ast_build_machine, ast_build_os, ast_build_date);
299 fflush(chan->fileptr);
301 chan->type = LOGTYPE_FILE;
303 chan->logmask = make_components(chan->components, lineno);
308 static void init_logger_chain(int locked, const char *altconf)
310 struct logchannel *chan;
311 struct ast_config *cfg;
312 struct ast_variable *var;
314 struct ast_flags config_flags = { 0 };
316 if (!(cfg = ast_config_load2(S_OR(altconf, "logger.conf"), "logger", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID) {
320 /* delete our list of log channels */
322 AST_RWLIST_WRLOCK(&logchannels);
324 while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list))) {
329 AST_RWLIST_UNLOCK(&logchannels);
336 /* If no config file, we're fine, set default options. */
339 fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
341 fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
343 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
346 chan->type = LOGTYPE_CONSOLE;
347 chan->logmask = __LOG_WARNING | __LOG_NOTICE | __LOG_ERROR;
349 AST_RWLIST_WRLOCK(&logchannels);
351 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
352 global_logmask |= chan->logmask;
354 AST_RWLIST_UNLOCK(&logchannels);
359 if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
361 if (gethostname(hostname, sizeof(hostname) - 1)) {
362 ast_copy_string(hostname, "unknown", sizeof(hostname));
363 fprintf(stderr, "What box has no hostname???\n");
369 if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
370 ast_copy_string(dateformat, s, sizeof(dateformat));
372 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
373 if ((s = ast_variable_retrieve(cfg, "general", "queue_log"))) {
374 logfiles.queue_log = ast_true(s);
376 if ((s = ast_variable_retrieve(cfg, "general", "queue_log_to_file"))) {
377 logfiles.queue_log_to_file = ast_true(s);
379 if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name"))) {
380 ast_copy_string(queue_log_name, s, sizeof(queue_log_name));
382 if ((s = ast_variable_retrieve(cfg, "general", "exec_after_rotate"))) {
383 ast_copy_string(exec_after_rotate, s, sizeof(exec_after_rotate));
385 if ((s = ast_variable_retrieve(cfg, "general", "rotatestrategy"))) {
386 if (strcasecmp(s, "timestamp") == 0) {
387 rotatestrategy = TIMESTAMP;
388 } else if (strcasecmp(s, "rotate") == 0) {
389 rotatestrategy = ROTATE;
390 } else if (strcasecmp(s, "sequential") == 0) {
391 rotatestrategy = SEQUENTIAL;
393 fprintf(stderr, "Unknown rotatestrategy: %s\n", s);
396 if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp"))) {
397 rotatestrategy = ast_true(s) ? TIMESTAMP : SEQUENTIAL;
398 fprintf(stderr, "rotatetimestamp option has been deprecated. Please use rotatestrategy instead.\n");
403 AST_RWLIST_WRLOCK(&logchannels);
405 var = ast_variable_browse(cfg, "logfiles");
406 for (; var; var = var->next) {
407 if (!(chan = make_logchannel(var->name, var->value, var->lineno))) {
408 /* Print error message directly to the consoles since the lock is held
409 * and we don't want to unlock with the list partially built */
410 ast_console_puts_mutable("ERROR: Unable to create log channel '", __LOG_ERROR);
411 ast_console_puts_mutable(var->name, __LOG_ERROR);
412 ast_console_puts_mutable("'\n", __LOG_ERROR);
415 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
416 global_logmask |= chan->logmask;
425 AST_RWLIST_UNLOCK(&logchannels);
428 ast_config_destroy(cfg);
431 void ast_child_verbose(int level, const char *fmt, ...)
433 char *msg = NULL, *emsg = NULL, *sptr, *eptr;
437 /* Don't bother, if the level isn't that high */
438 if (option_verbose < level) {
444 if ((size = vsnprintf(msg, 0, fmt, ap)) < 0) {
451 if (!(msg = ast_malloc(size + 1))) {
456 vsnprintf(msg, size + 1, fmt, aq);
459 if (!(emsg = ast_malloc(size * 2 + 1))) {
464 for (sptr = msg, eptr = emsg; ; sptr++) {
475 fprintf(stdout, "verbose \"%s\" %d\n", emsg, level);
480 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
489 if (!logger_initialized) {
490 /* You are too early. We are not open yet! */
493 if (!queuelog_init) {
494 AST_RWLIST_WRLOCK(&logchannels);
495 if (!queuelog_init) {
497 * We have delayed initializing the queue logging system so
498 * preloaded realtime modules can get up. We must initialize
499 * now since someone is trying to log something.
503 AST_RWLIST_UNLOCK(&logchannels);
504 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
506 AST_RWLIST_UNLOCK(&logchannels);
510 if (ast_check_realtime("queue_log")) {
512 ast_localtime(&tv, &tm, NULL);
513 ast_strftime(time_str, sizeof(time_str), "%F %T.%6q", &tm);
515 vsnprintf(qlog_msg, sizeof(qlog_msg), fmt, ap);
517 if (logfiles.queue_adaptive_realtime) {
518 AST_DECLARE_APP_ARGS(args,
519 AST_APP_ARG(data)[5];
521 AST_NONSTANDARD_APP_ARGS(args, qlog_msg, '|');
522 /* Ensure fields are large enough to receive data */
523 ast_realtime_require_field("queue_log",
524 "data1", RQ_CHAR, strlen(S_OR(args.data[0], "")),
525 "data2", RQ_CHAR, strlen(S_OR(args.data[1], "")),
526 "data3", RQ_CHAR, strlen(S_OR(args.data[2], "")),
527 "data4", RQ_CHAR, strlen(S_OR(args.data[3], "")),
528 "data5", RQ_CHAR, strlen(S_OR(args.data[4], "")),
532 ast_store_realtime("queue_log", "time", time_str,
534 "queuename", queuename,
537 "data1", S_OR(args.data[0], ""),
538 "data2", S_OR(args.data[1], ""),
539 "data3", S_OR(args.data[2], ""),
540 "data4", S_OR(args.data[3], ""),
541 "data5", S_OR(args.data[4], ""),
544 ast_store_realtime("queue_log", "time", time_str,
546 "queuename", queuename,
553 if (!logfiles.queue_log_to_file) {
560 qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
561 vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
563 AST_RWLIST_RDLOCK(&logchannels);
565 fprintf(qlog, "%s\n", qlog_msg);
568 AST_RWLIST_UNLOCK(&logchannels);
572 static int rotate_file(const char *filename)
576 int x, y, which, found, res = 0, fd;
577 char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
579 switch (rotatestrategy) {
582 snprintf(new, sizeof(new), "%s.%d", filename, x);
583 fd = open(new, O_RDONLY);
589 if (rename(filename, new)) {
590 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
597 snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
598 if (rename(filename, new)) {
599 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
606 /* Find the next empty slot, including a possible suffix */
609 for (which = 0; which < ARRAY_LEN(suffixes); which++) {
610 snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
611 fd = open(new, O_RDONLY);
623 /* Found an empty slot */
624 for (y = x; y > 0; y--) {
625 for (which = 0; which < ARRAY_LEN(suffixes); which++) {
626 snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
627 fd = open(old, O_RDONLY);
629 /* Found the right suffix */
631 snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
632 if (rename(old, new)) {
633 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
641 /* Finally, rename the current file */
642 snprintf(new, sizeof(new), "%s.0", filename);
643 if (rename(filename, new)) {
644 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
651 if (!ast_strlen_zero(exec_after_rotate)) {
652 struct ast_channel *c = ast_dummy_channel_alloc();
654 pbx_builtin_setvar_helper(c, "filename", filename);
655 pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
656 if (ast_safe_system(buf) == -1) {
657 ast_log(LOG_WARNING, "error executing '%s'\n", buf);
659 c = ast_channel_release(c);
666 * \brief Start the realtime queue logging if configured.
668 * \retval TRUE if not to open queue log file.
670 static int logger_queue_rt_start(void)
672 if (ast_check_realtime("queue_log")) {
673 if (!ast_realtime_require_field("queue_log",
674 "time", RQ_DATETIME, 26,
675 "data1", RQ_CHAR, 20,
676 "data2", RQ_CHAR, 20,
677 "data3", RQ_CHAR, 20,
678 "data4", RQ_CHAR, 20,
679 "data5", RQ_CHAR, 20,
681 logfiles.queue_adaptive_realtime = 1;
683 logfiles.queue_adaptive_realtime = 0;
686 if (!logfiles.queue_log_to_file) {
687 /* Don't open the log file. */
696 * \brief Rotate the queue log file and restart.
698 * \param queue_rotate Log queue rotation mode.
700 * \note Assumes logchannels is write locked on entry.
702 * \retval 0 on success.
703 * \retval -1 on error.
705 static int logger_queue_restart(int queue_rotate)
708 char qfname[PATH_MAX];
710 if (logger_queue_rt_start()) {
714 snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
716 /* Just in case it was still open. */
724 /* Open the log file. */
725 qlog = fopen(qfname, "a");
727 ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
733 static int reload_logger(int rotate, const char *altconf)
735 int queue_rotate = rotate;
736 struct logchannel *f;
739 AST_RWLIST_WRLOCK(&logchannels);
743 /* Check filesize - this one typically doesn't need an auto-rotate */
744 if (ftello(qlog) > 0x40000000) { /* Arbitrarily, 1 GB */
758 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
760 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
762 f->disabled = 0; /* Re-enable logging at reload */
763 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
765 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
767 if (ftello(f->fileptr) > 0x40000000) { /* Arbitrarily, 1 GB */
768 /* Be more proactive about rotating massive log files */
771 fclose(f->fileptr); /* Close file */
773 if (rotate || rotate_this) {
774 rotate_file(f->filename);
779 filesize_reload_needed = 0;
781 init_logger_chain(1 /* locked */, altconf);
783 ast_unload_realtime("queue_log");
784 if (logfiles.queue_log) {
785 res = logger_queue_restart(queue_rotate);
786 AST_RWLIST_UNLOCK(&logchannels);
787 ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
788 ast_verb(1, "Asterisk Queue Logger restarted\n");
790 AST_RWLIST_UNLOCK(&logchannels);
796 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
797 a full Asterisk reload) */
798 int logger_reload(void)
800 if (reload_logger(0, NULL)) {
801 return RESULT_FAILURE;
803 return RESULT_SUCCESS;
806 static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
810 e->command = "logger reload";
812 "Usage: logger reload [<alt-conf>]\n"
813 " Reloads the logger subsystem state. Use after restarting syslogd(8) if you are using syslog logging.\n";
818 if (reload_logger(0, a->argc == 3 ? a->argv[2] : NULL)) {
819 ast_cli(a->fd, "Failed to reload the logger\n");
825 static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
829 e->command = "logger rotate";
831 "Usage: logger rotate\n"
832 " Rotates and Reopens the log files.\n";
837 if (reload_logger(1, NULL)) {
838 ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
844 static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
852 e->command = "logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}";
854 "Usage: logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}\n"
855 " Set a specific log level to enabled/disabled for this console.\n";
862 return CLI_SHOWUSAGE;
864 AST_RWLIST_WRLOCK(&logchannels);
866 for (x = 0; x < ARRAY_LEN(levels); x++) {
867 if (levels[x] && !strcasecmp(a->argv[3], levels[x])) {
873 AST_RWLIST_UNLOCK(&logchannels);
875 state = ast_true(a->argv[4]) ? 1 : 0;
878 ast_console_toggle_loglevel(a->fd, level, state);
879 ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
881 return CLI_SHOWUSAGE;
886 /*! \brief CLI command to show logging system configuration */
887 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
889 #define FORMATL "%-35.35s %-8.8s %-9.9s "
890 struct logchannel *chan;
893 e->command = "logger show channels";
895 "Usage: logger show channels\n"
896 " List configured logger channels.\n";
901 ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
902 ast_cli(a->fd, "Configuration\n");
903 ast_cli(a->fd, FORMATL, "-------", "----", "------");
904 ast_cli(a->fd, "-------------\n");
905 AST_RWLIST_RDLOCK(&logchannels);
906 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
909 ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
910 chan->disabled ? "Disabled" : "Enabled");
911 ast_cli(a->fd, " - ");
912 for (level = 0; level < ARRAY_LEN(levels); level++) {
913 if ((chan->logmask & (1 << level)) && levels[level]) {
914 ast_cli(a->fd, "%s ", levels[level]);
917 ast_cli(a->fd, "\n");
919 AST_RWLIST_UNLOCK(&logchannels);
920 ast_cli(a->fd, "\n");
926 void (*verboser)(const char *string);
927 AST_LIST_ENTRY(verb) list;
930 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
932 static struct ast_cli_entry cli_logger[] = {
933 AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
934 AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
935 AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
936 AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console")
939 static void _handle_SIGXFSZ(int sig)
941 /* Indicate need to reload */
942 filesize_reload_needed = 1;
945 static struct sigaction handle_SIGXFSZ = {
946 .sa_handler = _handle_SIGXFSZ,
947 .sa_flags = SA_RESTART,
950 static void ast_log_vsyslog(struct logmsg *msg)
953 int syslog_level = ast_syslog_priority_from_loglevel(msg->level);
955 if (syslog_level < 0) {
956 /* we are locked here, so cannot ast_log() */
957 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", msg->level);
961 snprintf(buf, sizeof(buf), "%s[%d]: %s:%d in %s: %s",
962 levels[msg->level], msg->lwp, msg->file, msg->line, msg->function, msg->message);
964 term_strip(buf, buf, strlen(buf) + 1);
965 syslog(syslog_level, "%s", buf);
968 /*! \brief Print a normal log message to the channels */
969 static void logger_print_normal(struct logmsg *logmsg)
971 struct logchannel *chan = NULL;
973 struct verb *v = NULL;
975 if (logmsg->level == __LOG_VERBOSE) {
976 char *tmpmsg = ast_strdupa(logmsg->message + 1);
977 /* Iterate through the list of verbosers and pass them the log message string */
978 AST_RWLIST_RDLOCK(&verbosers);
979 AST_RWLIST_TRAVERSE(&verbosers, v, list)
980 v->verboser(logmsg->message);
981 AST_RWLIST_UNLOCK(&verbosers);
982 ast_string_field_set(logmsg, message, tmpmsg);
985 AST_RWLIST_RDLOCK(&logchannels);
987 if (!AST_RWLIST_EMPTY(&logchannels)) {
988 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
989 /* If the channel is disabled, then move on to the next one */
992 /* Check syslog channels */
993 if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
994 ast_log_vsyslog(logmsg);
995 /* Console channels */
996 } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
998 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
1000 /* If the level is verbose, then skip it */
1001 if (logmsg->level == __LOG_VERBOSE)
1004 /* Turn the numerical line number into a string */
1005 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
1006 /* Build string to print out */
1007 snprintf(buf, sizeof(buf), "[%s] %s[%d]: %s:%s %s: %s",
1009 term_color(tmp1, logmsg->level_name, colors[logmsg->level], 0, sizeof(tmp1)),
1011 term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
1012 term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
1013 term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
1016 ast_console_puts_mutable(buf, logmsg->level);
1018 } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
1021 /* If no file pointer exists, skip it */
1022 if (!chan->fileptr) {
1026 /* Print out to the file */
1027 res = fprintf(chan->fileptr, "[%s] %s[%d] %s: %s",
1028 logmsg->date, logmsg->level_name, logmsg->lwp, logmsg->file, term_strip(buf, logmsg->message, BUFSIZ));
1029 if (res <= 0 && !ast_strlen_zero(logmsg->message)) {
1030 fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
1031 if (errno == ENOMEM || errno == ENOSPC)
1032 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
1034 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
1035 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
1037 } else if (res > 0) {
1038 fflush(chan->fileptr);
1042 } else if (logmsg->level != __LOG_VERBOSE) {
1043 fputs(logmsg->message, stdout);
1046 AST_RWLIST_UNLOCK(&logchannels);
1048 /* If we need to reload because of the file size, then do so */
1049 if (filesize_reload_needed) {
1050 reload_logger(-1, NULL);
1051 ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
1057 /*! \brief Actual logging thread */
1058 static void *logger_thread(void *data)
1060 struct logmsg *next = NULL, *msg = NULL;
1063 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
1064 AST_LIST_LOCK(&logmsgs);
1065 if (AST_LIST_EMPTY(&logmsgs)) {
1066 if (close_logger_thread) {
1069 ast_cond_wait(&logcond, &logmsgs.lock);
1072 next = AST_LIST_FIRST(&logmsgs);
1073 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
1074 AST_LIST_UNLOCK(&logmsgs);
1076 /* Otherwise go through and process each message in the order added */
1077 while ((msg = next)) {
1078 /* Get the next entry now so that we can free our current structure later */
1079 next = AST_LIST_NEXT(msg, list);
1081 /* Depending on the type, send it to the proper function */
1082 logger_print_normal(msg);
1084 /* Free the data since we are done */
1088 /* If we should stop, then stop */
1089 if (close_logger_thread)
1098 * \brief Initialize the logger queue.
1100 * \note Assumes logchannels is write locked on entry.
1104 static void logger_queue_init(void)
1106 ast_unload_realtime("queue_log");
1107 if (logfiles.queue_log) {
1108 char qfname[PATH_MAX];
1110 if (logger_queue_rt_start()) {
1114 /* Open the log file. */
1115 snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR,
1118 /* Just in case it was already open. */
1121 qlog = fopen(qfname, "a");
1123 ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
1128 int init_logger(void)
1130 /* auto rotate if sig SIGXFSZ comes a-knockin */
1131 sigaction(SIGXFSZ, &handle_SIGXFSZ, NULL);
1133 /* start logger thread */
1134 ast_cond_init(&logcond, NULL);
1135 if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
1136 ast_cond_destroy(&logcond);
1140 /* register the logger cli commands */
1141 ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
1143 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
1145 /* create log channels */
1146 init_logger_chain(0 /* locked */, NULL);
1147 logger_initialized = 1;
1152 void close_logger(void)
1154 struct logchannel *f = NULL;
1156 logger_initialized = 0;
1158 /* Stop logger thread */
1159 AST_LIST_LOCK(&logmsgs);
1160 close_logger_thread = 1;
1161 ast_cond_signal(&logcond);
1162 AST_LIST_UNLOCK(&logmsgs);
1164 if (logthread != AST_PTHREADT_NULL)
1165 pthread_join(logthread, NULL);
1167 AST_RWLIST_WRLOCK(&logchannels);
1174 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
1175 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
1181 closelog(); /* syslog */
1183 AST_RWLIST_UNLOCK(&logchannels);
1189 * \brief send log messages to syslog and/or the console
1191 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
1193 struct logmsg *logmsg = NULL;
1194 struct ast_str *buf = NULL;
1196 struct timeval now = ast_tvnow();
1199 char datestring[256];
1201 if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1204 if (level != __LOG_VERBOSE && AST_RWLIST_EMPTY(&logchannels)) {
1206 * we don't have the logger chain configured yet,
1207 * so just log to stdout
1211 result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1213 if (result != AST_DYNSTR_BUILD_FAILED) {
1214 term_filter_escapes(ast_str_buffer(buf));
1215 fputs(ast_str_buffer(buf), stdout);
1220 /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
1221 are non-zero; LOG_DEBUG messages can still be displayed if option_debug
1222 is zero, if option_verbose is non-zero (this allows for 'level zero'
1223 LOG_DEBUG messages to be displayed, if the logmask on any channel
1226 if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
1229 /* Ignore anything that never gets logged anywhere */
1230 if (level != __LOG_VERBOSE && !(global_logmask & (1 << level)))
1235 res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1238 /* If the build failed, then abort and free this structure */
1239 if (res == AST_DYNSTR_BUILD_FAILED)
1242 /* Create a new logging message */
1243 if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
1246 /* Copy string over */
1247 ast_string_field_set(logmsg, message, ast_str_buffer(buf));
1250 if (level == __LOG_VERBOSE) {
1251 logmsg->type = LOGMSG_VERBOSE;
1253 logmsg->type = LOGMSG_NORMAL;
1256 /* Create our date/time */
1257 ast_localtime(&now, &tm, NULL);
1258 ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
1259 ast_string_field_set(logmsg, date, datestring);
1261 /* Copy over data */
1262 logmsg->level = level;
1263 logmsg->line = line;
1264 ast_string_field_set(logmsg, level_name, levels[level]);
1265 ast_string_field_set(logmsg, file, file);
1266 ast_string_field_set(logmsg, function, function);
1267 logmsg->lwp = ast_get_tid();
1269 /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1270 if (logthread != AST_PTHREADT_NULL) {
1271 AST_LIST_LOCK(&logmsgs);
1272 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1273 ast_cond_signal(&logcond);
1274 AST_LIST_UNLOCK(&logmsgs);
1276 logger_print_normal(logmsg);
1285 struct ast_bt *ast_bt_create(void)
1287 struct ast_bt *bt = ast_calloc(1, sizeof(*bt));
1289 ast_log(LOG_ERROR, "Unable to allocate memory for backtrace structure!\n");
1295 ast_bt_get_addresses(bt);
1300 int ast_bt_get_addresses(struct ast_bt *bt)
1302 bt->num_frames = backtrace(bt->addresses, AST_MAX_BT_FRAMES);
1307 void *ast_bt_destroy(struct ast_bt *bt)
1316 char **ast_bt_get_symbols(void **addresses, size_t num_frames)
1318 char **strings = NULL;
1319 #if defined(BETTER_BACKTRACES)
1321 bfd *bfdobj; /* bfd.h */
1322 Dl_info dli; /* dlfcn.h */
1324 asymbol **syms = NULL; /* bfd.h */
1325 bfd_vma offset; /* bfd.h */
1326 const char *lastslash;
1328 const char *file, *func;
1330 char address_str[128];
1332 size_t strings_size;
1336 #if defined(BETTER_BACKTRACES)
1337 strings_size = num_frames * sizeof(*strings);
1338 eachlen = ast_calloc(num_frames, sizeof(*eachlen));
1340 if (!(strings = ast_calloc(num_frames, sizeof(*strings)))) {
1344 for (stackfr = 0; stackfr < num_frames; stackfr++) {
1345 int found = 0, symbolcount;
1349 if (!dladdr(addresses[stackfr], &dli)) {
1353 if (strcmp(dli.dli_fname, "asterisk") == 0) {
1354 char asteriskpath[256];
1355 if (!(dli.dli_fname = ast_utils_which("asterisk", asteriskpath, sizeof(asteriskpath)))) {
1356 /* This will fail to find symbols */
1357 ast_debug(1, "Failed to find asterisk binary for debug symbols.\n");
1358 dli.dli_fname = "asterisk";
1362 lastslash = strrchr(dli.dli_fname, '/');
1363 if ( (bfdobj = bfd_openr(dli.dli_fname, NULL)) &&
1364 bfd_check_format(bfdobj, bfd_object) &&
1365 (allocsize = bfd_get_symtab_upper_bound(bfdobj)) > 0 &&
1366 (syms = ast_malloc(allocsize)) &&
1367 (symbolcount = bfd_canonicalize_symtab(bfdobj, syms))) {
1369 if (bfdobj->flags & DYNAMIC) {
1370 offset = addresses[stackfr] - dli.dli_fbase;
1372 offset = addresses[stackfr] - (void *) 0;
1375 for (section = bfdobj->sections; section; section = section->next) {
1376 if ( !bfd_get_section_flags(bfdobj, section) & SEC_ALLOC ||
1377 section->vma > offset ||
1378 section->size + section->vma < offset) {
1382 if (!bfd_find_nearest_line(bfdobj, section, syms, offset - section->vma, &file, &func, &line)) {
1386 /* Stack trace output */
1388 if ((lastslash = strrchr(file, '/'))) {
1389 const char *prevslash;
1390 for (prevslash = lastslash - 1; *prevslash != '/' && prevslash >= file; prevslash--);
1391 if (prevslash >= file) {
1392 lastslash = prevslash;
1395 if (dli.dli_saddr == NULL) {
1396 address_str[0] = '\0';
1398 snprintf(address_str, sizeof(address_str), " (%p+%lX)",
1400 (unsigned long) (addresses[stackfr] - dli.dli_saddr));
1402 snprintf(msg, sizeof(msg), "%s:%u %s()%s",
1403 lastslash ? lastslash + 1 : file, line,
1407 break; /* out of section iteration */
1417 /* Default output, if we cannot find the information within BFD */
1419 if (dli.dli_saddr == NULL) {
1420 address_str[0] = '\0';
1422 snprintf(address_str, sizeof(address_str), " (%p+%lX)",
1424 (unsigned long) (addresses[stackfr] - dli.dli_saddr));
1426 snprintf(msg, sizeof(msg), "%s %s()%s",
1427 lastslash ? lastslash + 1 : dli.dli_fname,
1428 S_OR(dli.dli_sname, "<unknown>"),
1432 if (!ast_strlen_zero(msg)) {
1434 eachlen[stackfr] = strlen(msg);
1435 if (!(tmp = ast_realloc(strings, strings_size + eachlen[stackfr] + 1))) {
1438 break; /* out of stack frame iteration */
1441 strings[stackfr] = (char *) strings + strings_size;
1442 ast_copy_string(strings[stackfr], msg, eachlen[stackfr] + 1);
1443 strings_size += eachlen[stackfr] + 1;
1448 /* Recalculate the offset pointers */
1449 strings[0] = (char *) strings + num_frames * sizeof(*strings);
1450 for (stackfr = 1; stackfr < num_frames; stackfr++) {
1451 strings[stackfr] = strings[stackfr - 1] + eachlen[stackfr - 1] + 1;
1454 #else /* !defined(BETTER_BACKTRACES) */
1455 strings = backtrace_symbols(addresses, num_frames);
1456 #endif /* defined(BETTER_BACKTRACES) */
1460 #endif /* HAVE_BKTR */
1462 void ast_backtrace(void)
1469 if (!(bt = ast_bt_create())) {
1470 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
1474 if ((strings = ast_bt_get_symbols(bt->addresses, bt->num_frames))) {
1475 ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
1476 for (i = 3; i < bt->num_frames - 2; i++) {
1477 ast_debug(1, "#%d: [%p] %s\n", i - 3, bt->addresses[i], strings[i]);
1480 /* MALLOC_DEBUG will erroneously report an error here, unless we undef the macro. */
1484 ast_debug(1, "Could not allocate memory for backtrace\n");
1488 ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1489 #endif /* defined(HAVE_BKTR) */
1492 void __ast_verbose_ap(const char *file, int line, const char *func, const char *fmt, va_list ap)
1494 struct ast_str *buf = NULL;
1497 if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
1500 if (ast_opt_timestamp) {
1507 ast_localtime(&now, &tm, NULL);
1508 ast_strftime(date, sizeof(date), dateformat, &tm);
1509 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1510 sprintf(datefmt, "%c[%s] %s", 127, date, fmt);
1513 char *tmp = alloca(strlen(fmt) + 2);
1514 sprintf(tmp, "%c%s", 127, fmt);
1519 res = ast_str_set_va(&buf, 0, fmt, ap);
1521 /* If the build failed then we can drop this allocated message */
1522 if (res == AST_DYNSTR_BUILD_FAILED)
1525 ast_log(__LOG_VERBOSE, file, line, func, "%s", ast_str_buffer(buf));
1528 void __ast_verbose(const char *file, int line, const char *func, const char *fmt, ...)
1533 __ast_verbose_ap(file, line, func, fmt, ap);
1537 /* No new code should use this directly, but we have the ABI for backwards compat */
1539 void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
1540 void ast_verbose(const char *fmt, ...)
1545 __ast_verbose_ap("", 0, "", fmt, ap);
1549 int ast_register_verbose(void (*v)(const char *string))
1553 if (!(verb = ast_malloc(sizeof(*verb))))
1558 AST_RWLIST_WRLOCK(&verbosers);
1559 AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1560 AST_RWLIST_UNLOCK(&verbosers);
1565 int ast_unregister_verbose(void (*v)(const char *string))
1569 AST_RWLIST_WRLOCK(&verbosers);
1570 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1571 if (cur->verboser == v) {
1572 AST_RWLIST_REMOVE_CURRENT(list);
1577 AST_RWLIST_TRAVERSE_SAFE_END;
1578 AST_RWLIST_UNLOCK(&verbosers);
1580 return cur ? 0 : -1;
1583 static void update_logchannels(void)
1585 struct logchannel *cur;
1587 AST_RWLIST_WRLOCK(&logchannels);
1591 AST_RWLIST_TRAVERSE(&logchannels, cur, list) {
1592 cur->logmask = make_components(cur->components, cur->lineno);
1593 global_logmask |= cur->logmask;
1596 AST_RWLIST_UNLOCK(&logchannels);
1599 int ast_logger_register_level(const char *name)
1602 unsigned int available = 0;
1604 AST_RWLIST_WRLOCK(&logchannels);
1606 for (level = 0; level < ARRAY_LEN(levels); level++) {
1607 if ((level >= 16) && !available && !levels[level]) {
1612 if (levels[level] && !strcasecmp(levels[level], name)) {
1613 ast_log(LOG_WARNING,
1614 "Unable to register dynamic logger level '%s': a standard logger level uses that name.\n",
1616 AST_RWLIST_UNLOCK(&logchannels);
1623 ast_log(LOG_WARNING,
1624 "Unable to register dynamic logger level '%s'; maximum number of levels registered.\n",
1626 AST_RWLIST_UNLOCK(&logchannels);
1631 levels[available] = ast_strdup(name);
1633 AST_RWLIST_UNLOCK(&logchannels);
1635 ast_debug(1, "Registered dynamic logger level '%s' with index %d.\n", name, available);
1637 update_logchannels();
1642 void ast_logger_unregister_level(const char *name)
1644 unsigned int found = 0;
1647 AST_RWLIST_WRLOCK(&logchannels);
1649 for (x = 16; x < ARRAY_LEN(levels); x++) {
1654 if (strcasecmp(levels[x], name)) {
1663 /* take this level out of the global_logmask, to ensure that no new log messages
1664 * will be queued for it
1667 global_logmask &= ~(1 << x);
1671 AST_RWLIST_UNLOCK(&logchannels);
1673 ast_debug(1, "Unregistered dynamic logger level '%s' with index %d.\n", name, x);
1675 update_logchannels();
1677 AST_RWLIST_UNLOCK(&logchannels);