2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Asterisk Logger
25 * \author Mark Spencer <markster@digium.com>
29 * define _ASTERISK_LOGGER_H to prevent the inclusion of logger.h;
30 * it redefines LOG_* which we need to define syslog_level_map.
31 * later, we force the inclusion of logger.h again.
33 #define _ASTERISK_LOGGER_H
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
39 * WARNING: additional #include directives should NOT be placed here, they
40 * should be placed AFTER '#undef _ASTERISK_LOGGER_H' below
42 #include "asterisk/_private.h"
43 #include "asterisk/paths.h" /* use ast_config_AST_LOG_DIR */
50 #define MAX_BACKTRACE_FRAMES 20
53 #define SYSLOG_NAMES /* so we can map syslog facilities names to their numeric values,
54 from <syslog.h> which is included by logger.h */
57 static const int syslog_level_map[] = {
59 LOG_INFO, /* arbitrary equivalent of LOG_EVENT */
67 #define SYSLOG_NLEVELS sizeof(syslog_level_map) / sizeof(int)
69 #undef _ASTERISK_LOGGER_H /* now include logger.h */
70 #include "asterisk/logger.h"
71 #include "asterisk/lock.h"
72 #include "asterisk/channel.h"
73 #include "asterisk/config.h"
74 #include "asterisk/term.h"
75 #include "asterisk/cli.h"
76 #include "asterisk/utils.h"
77 #include "asterisk/manager.h"
78 #include "asterisk/threadstorage.h"
79 #include "asterisk/strings.h"
80 #include "asterisk/pbx.h"
81 #include "asterisk/app.h"
83 #if defined(__linux__) && !defined(__NR_gettid)
84 #include <asm/unistd.h>
87 #if defined(__linux__) && defined(__NR_gettid)
88 #define GETTID() syscall(__NR_gettid)
90 #define GETTID() getpid()
92 static char dateformat[256] = "%b %e %T"; /* Original Asterisk Format */
94 static char queue_log_name[256] = QUEUELOG;
95 static char exec_after_rotate[256] = "";
97 static int filesize_reload_needed;
98 static unsigned int global_logmask = 0xFFFF;
100 static enum rotatestrategy {
101 SEQUENTIAL = 1 << 0, /* Original method - create a new file, in order */
102 ROTATE = 1 << 1, /* Rotate all files, such that the oldest file has the highest suffix */
103 TIMESTAMP = 1 << 2, /* Append the epoch timestamp onto the end of the archived file */
104 } rotatestrategy = SEQUENTIAL;
107 unsigned int queue_log:1;
110 static char hostname[MAXHOSTNAMELEN];
119 /*! What to log to this channel */
120 unsigned int logmask;
121 /*! If this channel is disabled or not */
123 /*! syslog facility */
125 /*! Type of log channel */
127 /*! logfile logging file pointer */
130 char filename[PATH_MAX];
131 /*! field for linking to list */
132 AST_LIST_ENTRY(logchannel) list;
133 /*! Line number from configuration file */
135 /*! Components (levels) from last config load */
139 static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
147 enum logmsgtypes type;
151 AST_DECLARE_STRING_FIELDS(
152 AST_STRING_FIELD(date);
153 AST_STRING_FIELD(file);
154 AST_STRING_FIELD(function);
155 AST_STRING_FIELD(message);
156 AST_STRING_FIELD(level_name);
158 AST_LIST_ENTRY(logmsg) list;
161 static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
162 static pthread_t logthread = AST_PTHREADT_NULL;
163 static ast_cond_t logcond;
164 static int close_logger_thread;
168 /*! \brief Logging channels used in the Asterisk logging system
170 * The first 16 levels are reserved for system usage, and the remaining
171 * levels are reserved for usage by dynamic levels registered via
172 * ast_logger_register_level.
175 /* Modifications to this array are protected by the rwlock in the
179 static char *levels[32] = {
181 "---EVENT---", /* no longer used */
189 /*! \brief Colors used in the console for logging */
190 static const int colors[32] = {
192 COLOR_BRBLUE, /* no longer used */
225 AST_THREADSTORAGE(verbose_buf);
226 #define VERBOSE_BUF_INIT_SIZE 256
228 AST_THREADSTORAGE(log_buf);
229 #define LOG_BUF_INIT_SIZE 256
231 static unsigned int make_components(const char *s, int lineno)
234 unsigned int res = 0;
235 char *stringp = ast_strdupa(s);
238 while ((w = strsep(&stringp, ","))) {
241 w = ast_skip_blanks(w);
243 for (x = 0; x < ARRAY_LEN(levels); x++) {
244 if (levels[x] && !strcasecmp(w, levels[x])) {
255 static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno)
257 struct logchannel *chan;
263 if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan) + strlen(components) + 1)))
266 strcpy(chan->components, components);
267 chan->lineno = lineno;
269 if (!strcasecmp(channel, "console")) {
270 chan->type = LOGTYPE_CONSOLE;
271 } else if (!strncasecmp(channel, "syslog", 6)) {
274 * syslog.facility => level,level,level
276 facility = strchr(channel, '.');
277 if (!facility++ || !facility) {
283 * Walk through the list of facilitynames (defined in sys/syslog.h)
284 * to see if we can find the one we have been given
287 cptr = facilitynames;
288 while (cptr->c_name) {
289 if (!strcasecmp(facility, cptr->c_name)) {
290 chan->facility = cptr->c_val;
297 if (!strcasecmp(facility, "kern"))
298 chan->facility = LOG_KERN;
299 else if (!strcasecmp(facility, "USER"))
300 chan->facility = LOG_USER;
301 else if (!strcasecmp(facility, "MAIL"))
302 chan->facility = LOG_MAIL;
303 else if (!strcasecmp(facility, "DAEMON"))
304 chan->facility = LOG_DAEMON;
305 else if (!strcasecmp(facility, "AUTH"))
306 chan->facility = LOG_AUTH;
307 else if (!strcasecmp(facility, "SYSLOG"))
308 chan->facility = LOG_SYSLOG;
309 else if (!strcasecmp(facility, "LPR"))
310 chan->facility = LOG_LPR;
311 else if (!strcasecmp(facility, "NEWS"))
312 chan->facility = LOG_NEWS;
313 else if (!strcasecmp(facility, "UUCP"))
314 chan->facility = LOG_UUCP;
315 else if (!strcasecmp(facility, "CRON"))
316 chan->facility = LOG_CRON;
317 else if (!strcasecmp(facility, "LOCAL0"))
318 chan->facility = LOG_LOCAL0;
319 else if (!strcasecmp(facility, "LOCAL1"))
320 chan->facility = LOG_LOCAL1;
321 else if (!strcasecmp(facility, "LOCAL2"))
322 chan->facility = LOG_LOCAL2;
323 else if (!strcasecmp(facility, "LOCAL3"))
324 chan->facility = LOG_LOCAL3;
325 else if (!strcasecmp(facility, "LOCAL4"))
326 chan->facility = LOG_LOCAL4;
327 else if (!strcasecmp(facility, "LOCAL5"))
328 chan->facility = LOG_LOCAL5;
329 else if (!strcasecmp(facility, "LOCAL6"))
330 chan->facility = LOG_LOCAL6;
331 else if (!strcasecmp(facility, "LOCAL7"))
332 chan->facility = LOG_LOCAL7;
335 if (0 > chan->facility) {
336 fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
341 chan->type = LOGTYPE_SYSLOG;
342 ast_copy_string(chan->filename, channel, sizeof(chan->filename));
343 openlog("asterisk", LOG_PID, chan->facility);
345 if (!ast_strlen_zero(hostname)) {
346 snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s",
347 channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel, hostname);
349 snprintf(chan->filename, sizeof(chan->filename), "%s/%s",
350 channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel);
352 if (!(chan->fileptr = fopen(chan->filename, "a"))) {
353 /* Can't log here, since we're called with a lock */
354 fprintf(stderr, "Logger Warning: Unable to open log file '%s': %s\n", chan->filename, strerror(errno));
356 chan->type = LOGTYPE_FILE;
358 chan->logmask = make_components(chan->components, lineno);
363 static void init_logger_chain(int locked)
365 struct logchannel *chan;
366 struct ast_config *cfg;
367 struct ast_variable *var;
369 struct ast_flags config_flags = { 0 };
371 if (!(cfg = ast_config_load2("logger.conf", "logger", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID)
374 /* delete our list of log channels */
376 AST_RWLIST_WRLOCK(&logchannels);
377 while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list)))
381 AST_RWLIST_UNLOCK(&logchannels);
387 /* If no config file, we're fine, set default options. */
390 fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
392 fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
393 if (!(chan = ast_calloc(1, sizeof(*chan))))
395 chan->type = LOGTYPE_CONSOLE;
396 chan->logmask = __LOG_WARNING | __LOG_NOTICE | __LOG_ERROR;
398 AST_RWLIST_WRLOCK(&logchannels);
399 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
400 global_logmask |= chan->logmask;
402 AST_RWLIST_UNLOCK(&logchannels);
406 if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
408 if (gethostname(hostname, sizeof(hostname) - 1)) {
409 ast_copy_string(hostname, "unknown", sizeof(hostname));
410 fprintf(stderr, "What box has no hostname???\n");
416 if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
417 ast_copy_string(dateformat, s, sizeof(dateformat));
419 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
420 if ((s = ast_variable_retrieve(cfg, "general", "queue_log")))
421 logfiles.queue_log = ast_true(s);
422 if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name")))
423 ast_copy_string(queue_log_name, s, sizeof(queue_log_name));
424 if ((s = ast_variable_retrieve(cfg, "general", "exec_after_rotate")))
425 ast_copy_string(exec_after_rotate, s, sizeof(exec_after_rotate));
426 if ((s = ast_variable_retrieve(cfg, "general", "rotatestrategy"))) {
427 if (strcasecmp(s, "timestamp") == 0)
428 rotatestrategy = TIMESTAMP;
429 else if (strcasecmp(s, "rotate") == 0)
430 rotatestrategy = ROTATE;
431 else if (strcasecmp(s, "sequential") == 0)
432 rotatestrategy = SEQUENTIAL;
434 fprintf(stderr, "Unknown rotatestrategy: %s\n", s);
436 if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp"))) {
437 rotatestrategy = ast_true(s) ? TIMESTAMP : SEQUENTIAL;
438 fprintf(stderr, "rotatetimestamp option has been deprecated. Please use rotatestrategy instead.\n");
443 AST_RWLIST_WRLOCK(&logchannels);
444 var = ast_variable_browse(cfg, "logfiles");
445 for (; var; var = var->next) {
446 if (!(chan = make_logchannel(var->name, var->value, var->lineno)))
448 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
449 global_logmask |= chan->logmask;
452 AST_RWLIST_UNLOCK(&logchannels);
454 ast_config_destroy(cfg);
457 void ast_child_verbose(int level, const char *fmt, ...)
459 char *msg = NULL, *emsg = NULL, *sptr, *eptr;
463 /* Don't bother, if the level isn't that high */
464 if (option_verbose < level) {
470 if ((size = vsnprintf(msg, 0, fmt, ap)) < 0) {
477 if (!(msg = ast_malloc(size + 1))) {
482 vsnprintf(msg, size + 1, fmt, aq);
485 if (!(emsg = ast_malloc(size * 2 + 1))) {
490 for (sptr = msg, eptr = emsg; ; sptr++) {
501 fprintf(stdout, "verbose \"%s\" %d\n", emsg, level);
506 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
513 if (ast_check_realtime("queue_log")) {
515 vsnprintf(qlog_msg, sizeof(qlog_msg), fmt, ap);
517 snprintf(time_str, sizeof(time_str), "%ld", (long)time(NULL));
518 ast_store_realtime("queue_log", "time", time_str,
520 "queuename", queuename,
528 qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
529 vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
532 AST_RWLIST_RDLOCK(&logchannels);
534 fprintf(qlog, "%s\n", qlog_msg);
537 AST_RWLIST_UNLOCK(&logchannels);
541 static int rotate_file(const char *filename)
545 int x, y, which, found, res = 0, fd;
546 char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
548 switch (rotatestrategy) {
551 snprintf(new, sizeof(new), "%s.%d", filename, x);
552 fd = open(new, O_RDONLY);
558 if (rename(filename, new)) {
559 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
564 snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
565 if (rename(filename, new)) {
566 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
571 /* Find the next empty slot, including a possible suffix */
574 for (which = 0; which < ARRAY_LEN(suffixes); which++) {
575 snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
576 fd = open(new, O_RDONLY);
588 /* Found an empty slot */
589 for (y = x; y > 0; y--) {
590 for (which = 0; which < ARRAY_LEN(suffixes); which++) {
591 snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
592 fd = open(old, O_RDONLY);
594 /* Found the right suffix */
596 snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
597 if (rename(old, new)) {
598 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
606 /* Finally, rename the current file */
607 snprintf(new, sizeof(new), "%s.0", filename);
608 if (rename(filename, new)) {
609 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
614 if (!ast_strlen_zero(exec_after_rotate)) {
615 struct ast_channel *c = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Logger/rotate");
617 pbx_builtin_setvar_helper(c, "filename", filename);
618 pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
619 if (ast_safe_system(buf) != -1) {
620 ast_log(LOG_WARNING, "error executing '%s'\n", buf);
622 c = ast_channel_release(c);
627 static int reload_logger(int rotate)
629 char old[PATH_MAX] = "";
630 int queue_rotate = rotate;
631 struct logchannel *f;
635 AST_RWLIST_WRLOCK(&logchannels);
639 /* Check filesize - this one typically doesn't need an auto-rotate */
640 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
641 if (stat(old, &st) != 0 || st.st_size > 0x40000000) { /* Arbitrarily, 1 GB */
653 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
655 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
657 f->disabled = 0; /* Re-enable logging at reload */
658 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
660 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
661 fclose(f->fileptr); /* Close file */
664 rotate_file(f->filename);
668 filesize_reload_needed = 0;
670 init_logger_chain(1 /* locked */);
672 if (logfiles.queue_log) {
673 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
677 qlog = fopen(old, "a");
679 AST_RWLIST_UNLOCK(&logchannels);
680 ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
681 AST_RWLIST_WRLOCK(&logchannels);
682 ast_verb(1, "Asterisk Queue Logger restarted\n");
684 ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
689 AST_RWLIST_UNLOCK(&logchannels);
694 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
695 a full Asterisk reload) */
696 int logger_reload(void)
699 return RESULT_FAILURE;
700 return RESULT_SUCCESS;
703 static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
707 e->command = "logger reload";
709 "Usage: logger reload\n"
710 " Reloads the logger subsystem state. Use after restarting syslogd(8) if you are using syslog logging.\n";
715 if (reload_logger(0)) {
716 ast_cli(a->fd, "Failed to reload the logger\n");
722 static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
726 e->command = "logger rotate";
728 "Usage: logger rotate\n"
729 " Rotates and Reopens the log files.\n";
734 if (reload_logger(1)) {
735 ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
741 static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
749 e->command = "logger set level";
751 "Usage: logger set level\n"
752 " Set a specific log level to enabled/disabled for this console.\n";
759 return CLI_SHOWUSAGE;
761 AST_RWLIST_WRLOCK(&logchannels);
763 for (x = 0; x < ARRAY_LEN(levels); x++) {
764 if (levels[x] && !strcasecmp(a->argv[3], levels[x])) {
770 AST_RWLIST_UNLOCK(&logchannels);
772 state = ast_true(a->argv[4]) ? 1 : 0;
775 ast_console_toggle_loglevel(a->fd, level, state);
776 ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
778 return CLI_SHOWUSAGE;
783 /*! \brief CLI command to show logging system configuration */
784 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
786 #define FORMATL "%-35.35s %-8.8s %-9.9s "
787 struct logchannel *chan;
790 e->command = "logger show channels";
792 "Usage: logger show channels\n"
793 " List configured logger channels.\n";
798 ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
799 ast_cli(a->fd, "Configuration\n");
800 ast_cli(a->fd, FORMATL, "-------", "----", "------");
801 ast_cli(a->fd, "-------------\n");
802 AST_RWLIST_RDLOCK(&logchannels);
803 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
806 ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
807 chan->disabled ? "Disabled" : "Enabled");
808 ast_cli(a->fd, " - ");
809 for (level = 0; level < ARRAY_LEN(levels); level++) {
810 if (chan->logmask & (1 << level)) {
811 ast_cli(a->fd, "%s ", levels[level]);
814 ast_cli(a->fd, "\n");
816 AST_RWLIST_UNLOCK(&logchannels);
817 ast_cli(a->fd, "\n");
823 void (*verboser)(const char *string);
824 AST_LIST_ENTRY(verb) list;
827 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
829 static struct ast_cli_entry cli_logger[] = {
830 AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
831 AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
832 AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
833 AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console")
836 static int handle_SIGXFSZ(int sig)
838 /* Indicate need to reload */
839 filesize_reload_needed = 1;
843 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, const char *str, long pid)
847 if (level >= SYSLOG_NLEVELS) {
848 /* we are locked here, so cannot ast_log() */
849 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
853 if (level == __LOG_VERBOSE) {
854 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: %s", pid, str);
856 } else if (level == __LOG_DTMF) {
857 snprintf(buf, sizeof(buf), "DTMF[%ld]: %s", pid, str);
860 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: %s",
861 levels[level], pid, file, line, function, str);
864 term_strip(buf, buf, strlen(buf) + 1);
865 syslog(syslog_level_map[level], "%s", buf);
868 /*! \brief Print a normal log message to the channels */
869 static void logger_print_normal(struct logmsg *logmsg)
871 struct logchannel *chan = NULL;
874 AST_RWLIST_RDLOCK(&logchannels);
876 if (!AST_RWLIST_EMPTY(&logchannels)) {
877 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
878 /* If the channel is disabled, then move on to the next one */
881 /* Check syslog channels */
882 if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
883 ast_log_vsyslog(logmsg->level, logmsg->file, logmsg->line, logmsg->function, logmsg->message, logmsg->process_id);
884 /* Console channels */
885 } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
887 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
889 /* If the level is verbose, then skip it */
890 if (logmsg->level == __LOG_VERBOSE)
893 /* Turn the numerical line number into a string */
894 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
895 /* Build string to print out */
896 snprintf(buf, sizeof(buf), "[%s] %s[%ld]: %s:%s %s: %s",
898 term_color(tmp1, logmsg->level_name, colors[logmsg->level], 0, sizeof(tmp1)),
900 term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
901 term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
902 term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
905 ast_console_puts_mutable(buf, logmsg->level);
907 } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
910 /* If no file pointer exists, skip it */
914 /* Print out to the file */
915 res = fprintf(chan->fileptr, "[%s] %s[%ld] %s: %s",
916 logmsg->date, logmsg->level_name, logmsg->process_id, logmsg->file, logmsg->message);
917 if (res <= 0 && !ast_strlen_zero(logmsg->message)) {
918 fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
919 if (errno == ENOMEM || errno == ENOSPC)
920 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
922 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
923 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
925 } else if (res > 0) {
926 fflush(chan->fileptr);
930 } else if (logmsg->level != __LOG_VERBOSE) {
931 fputs(logmsg->message, stdout);
934 AST_RWLIST_UNLOCK(&logchannels);
936 /* If we need to reload because of the file size, then do so */
937 if (filesize_reload_needed) {
939 ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
945 /*! \brief Print a verbose message to the verbosers */
946 static void logger_print_verbose(struct logmsg *logmsg)
948 struct verb *v = NULL;
950 /* Iterate through the list of verbosers and pass them the log message string */
951 AST_RWLIST_RDLOCK(&verbosers);
952 AST_RWLIST_TRAVERSE(&verbosers, v, list)
953 v->verboser(logmsg->message);
954 AST_RWLIST_UNLOCK(&verbosers);
959 /*! \brief Actual logging thread */
960 static void *logger_thread(void *data)
962 struct logmsg *next = NULL, *msg = NULL;
965 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
966 AST_LIST_LOCK(&logmsgs);
967 if (AST_LIST_EMPTY(&logmsgs)) {
968 if (close_logger_thread) {
971 ast_cond_wait(&logcond, &logmsgs.lock);
974 next = AST_LIST_FIRST(&logmsgs);
975 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
976 AST_LIST_UNLOCK(&logmsgs);
978 /* Otherwise go through and process each message in the order added */
979 while ((msg = next)) {
980 /* Get the next entry now so that we can free our current structure later */
981 next = AST_LIST_NEXT(msg, list);
983 /* Depending on the type, send it to the proper function */
984 if (msg->type == LOGMSG_NORMAL)
985 logger_print_normal(msg);
986 else if (msg->type == LOGMSG_VERBOSE)
987 logger_print_verbose(msg);
989 /* Free the data since we are done */
993 /* If we should stop, then stop */
994 if (close_logger_thread)
1001 int init_logger(void)
1006 /* auto rotate if sig SIGXFSZ comes a-knockin */
1007 (void) signal(SIGXFSZ, (void *) handle_SIGXFSZ);
1009 /* start logger thread */
1010 ast_cond_init(&logcond, NULL);
1011 if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
1012 ast_cond_destroy(&logcond);
1016 /* register the logger cli commands */
1017 ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
1019 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
1021 /* create log channels */
1022 init_logger_chain(0 /* locked */);
1024 if (logfiles.queue_log) {
1025 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
1026 qlog = fopen(tmp, "a");
1027 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
1032 void close_logger(void)
1034 struct logchannel *f = NULL;
1036 /* Stop logger thread */
1037 AST_LIST_LOCK(&logmsgs);
1038 close_logger_thread = 1;
1039 ast_cond_signal(&logcond);
1040 AST_LIST_UNLOCK(&logmsgs);
1042 if (logthread != AST_PTHREADT_NULL)
1043 pthread_join(logthread, NULL);
1045 AST_RWLIST_WRLOCK(&logchannels);
1052 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
1053 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
1059 closelog(); /* syslog */
1061 AST_RWLIST_UNLOCK(&logchannels);
1067 * \brief send log messages to syslog and/or the console
1069 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
1071 struct logmsg *logmsg = NULL;
1072 struct ast_str *buf = NULL;
1074 struct timeval now = ast_tvnow();
1077 char datestring[256];
1079 if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1082 if (AST_RWLIST_EMPTY(&logchannels)) {
1084 * we don't have the logger chain configured yet,
1085 * so just log to stdout
1087 if (level != __LOG_VERBOSE) {
1090 result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1092 if (result != AST_DYNSTR_BUILD_FAILED) {
1093 term_filter_escapes(ast_str_buffer(buf));
1094 fputs(ast_str_buffer(buf), stdout);
1100 /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
1101 are non-zero; LOG_DEBUG messages can still be displayed if option_debug
1102 is zero, if option_verbose is non-zero (this allows for 'level zero'
1103 LOG_DEBUG messages to be displayed, if the logmask on any channel
1106 if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
1109 /* Ignore anything that never gets logged anywhere */
1110 if (!(global_logmask & (1 << level)))
1115 res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1118 /* If the build failed, then abort and free this structure */
1119 if (res == AST_DYNSTR_BUILD_FAILED)
1122 /* Create a new logging message */
1123 if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
1126 /* Copy string over */
1127 ast_string_field_set(logmsg, message, ast_str_buffer(buf));
1129 /* Set type to be normal */
1130 logmsg->type = LOGMSG_NORMAL;
1132 /* Create our date/time */
1133 ast_localtime(&now, &tm, NULL);
1134 ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
1135 ast_string_field_set(logmsg, date, datestring);
1137 /* Copy over data */
1138 logmsg->level = level;
1139 logmsg->line = line;
1140 ast_string_field_set(logmsg, level_name, levels[level]);
1141 ast_string_field_set(logmsg, file, file);
1142 ast_string_field_set(logmsg, function, function);
1143 logmsg->process_id = (long) GETTID();
1145 /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1146 if (logthread != AST_PTHREADT_NULL) {
1147 AST_LIST_LOCK(&logmsgs);
1148 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1149 ast_cond_signal(&logcond);
1150 AST_LIST_UNLOCK(&logmsgs);
1152 logger_print_normal(logmsg);
1161 struct ast_bt *ast_bt_create(void)
1163 struct ast_bt *bt = ast_calloc(1, sizeof(*bt));
1165 ast_log(LOG_ERROR, "Unable to allocate memory for backtrace structure!\n");
1171 ast_bt_get_addresses(bt);
1176 int ast_bt_get_addresses(struct ast_bt *bt)
1178 bt->num_frames = backtrace(bt->addresses, AST_MAX_BT_FRAMES);
1183 void *ast_bt_destroy(struct ast_bt *bt)
1192 #endif /* HAVE_BKTR */
1194 void ast_backtrace(void)
1201 if (!(bt = ast_bt_create())) {
1202 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
1206 if ((strings = backtrace_symbols(bt->addresses, bt->num_frames))) {
1207 ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
1208 for (i = 0; i < bt->num_frames; i++) {
1209 ast_log(LOG_DEBUG, "#%d: [%p] %s\n", i, bt->addresses[i], strings[i]);
1212 /* MALLOC_DEBUG will erroneously report an error here, unless we undef the macro. */
1216 ast_debug(1, "Could not allocate memory for backtrace\n");
1220 ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1224 void __ast_verbose_ap(const char *file, int line, const char *func, const char *fmt, va_list ap)
1226 struct logmsg *logmsg = NULL;
1227 struct ast_str *buf = NULL;
1230 if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
1233 if (ast_opt_timestamp) {
1240 ast_localtime(&now, &tm, NULL);
1241 ast_strftime(date, sizeof(date), dateformat, &tm);
1242 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1243 sprintf(datefmt, "%c[%s] %s", 127, date, fmt);
1246 char *tmp = alloca(strlen(fmt) + 2);
1247 sprintf(tmp, "%c%s", 127, fmt);
1252 res = ast_str_set_va(&buf, 0, fmt, ap);
1254 /* If the build failed then we can drop this allocated message */
1255 if (res == AST_DYNSTR_BUILD_FAILED)
1258 if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
1261 ast_string_field_set(logmsg, message, ast_str_buffer(buf));
1263 ast_log(__LOG_VERBOSE, file, line, func, "%s", logmsg->message + 1);
1266 logmsg->type = LOGMSG_VERBOSE;
1268 /* Add to the list and poke the thread if possible */
1269 if (logthread != AST_PTHREADT_NULL) {
1270 AST_LIST_LOCK(&logmsgs);
1271 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1272 ast_cond_signal(&logcond);
1273 AST_LIST_UNLOCK(&logmsgs);
1275 logger_print_verbose(logmsg);
1280 void __ast_verbose(const char *file, int line, const char *func, const char *fmt, ...)
1285 __ast_verbose_ap(file, line, func, fmt, ap);
1289 /* No new code should use this directly, but we have the ABI for backwards compat */
1291 void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
1292 void ast_verbose(const char *fmt, ...)
1297 __ast_verbose_ap("", 0, "", fmt, ap);
1301 int ast_register_verbose(void (*v)(const char *string))
1305 if (!(verb = ast_malloc(sizeof(*verb))))
1310 AST_RWLIST_WRLOCK(&verbosers);
1311 AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1312 AST_RWLIST_UNLOCK(&verbosers);
1317 int ast_unregister_verbose(void (*v)(const char *string))
1321 AST_RWLIST_WRLOCK(&verbosers);
1322 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1323 if (cur->verboser == v) {
1324 AST_RWLIST_REMOVE_CURRENT(list);
1329 AST_RWLIST_TRAVERSE_SAFE_END;
1330 AST_RWLIST_UNLOCK(&verbosers);
1332 return cur ? 0 : -1;
1335 static void update_logchannels(void)
1337 struct logchannel *cur;
1339 AST_RWLIST_WRLOCK(&logchannels);
1343 AST_RWLIST_TRAVERSE(&logchannels, cur, list) {
1344 cur->logmask = make_components(cur->components, cur->lineno);
1345 global_logmask |= cur->logmask;
1348 AST_RWLIST_UNLOCK(&logchannels);
1351 int ast_logger_register_level(const char *name)
1354 unsigned int available = 0;
1356 AST_RWLIST_WRLOCK(&logchannels);
1358 for (level = 0; level < ARRAY_LEN(levels); level++) {
1359 if ((level >= 16) && !available && !levels[level]) {
1364 if (levels[level] && !strcasecmp(levels[level], name)) {
1365 ast_log(LOG_WARNING,
1366 "Unable to register dynamic logger level '%s': a standard logger level uses that name.\n",
1368 AST_RWLIST_UNLOCK(&logchannels);
1375 ast_log(LOG_WARNING,
1376 "Unable to register dynamic logger level '%s'; maximum number of levels registered.\n",
1378 AST_RWLIST_UNLOCK(&logchannels);
1383 levels[available] = ast_strdup(name);
1385 AST_RWLIST_UNLOCK(&logchannels);
1387 ast_debug(1, "Registered dynamic logger level '%s' with index %d.\n", name, available);
1389 update_logchannels();
1394 void ast_logger_unregister_level(const char *name)
1396 unsigned int found = 0;
1399 AST_RWLIST_WRLOCK(&logchannels);
1401 for (x = 16; x < ARRAY_LEN(levels); x++) {
1406 if (strcasecmp(levels[x], name)) {
1415 /* take this level out of the global_logmask, to ensure that no new log messages
1416 * will be queued for it
1419 global_logmask &= ~(1 << x);
1423 AST_RWLIST_UNLOCK(&logchannels);
1425 ast_debug(1, "Unregistered dynamic logger level '%s' with index %d.\n", name, x);
1427 update_logchannels();
1429 AST_RWLIST_UNLOCK(&logchannels);