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 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()
93 static char dateformat[256] = "%b %e %T"; /* Original Asterisk Format */
95 static char queue_log_name[256] = QUEUELOG;
96 static char exec_after_rotate[256] = "";
98 static int filesize_reload_needed;
99 static int global_logmask = -1;
101 enum rotatestrategy {
102 SEQUENTIAL = 1 << 0, /* Original method - create a new file, in order */
103 ROTATE = 1 << 1, /* Rotate all files, such that the oldest file has the highest suffix */
104 TIMESTAMP = 1 << 2, /* Append the epoch timestamp onto the end of the archived file */
105 } rotatestrategy = SEQUENTIAL;
108 unsigned int queue_log:1;
111 static char hostname[MAXHOSTNAMELEN];
120 int logmask; /* What to log to this channel */
121 int disabled; /* If this channel is disabled or not */
122 int facility; /* syslog facility */
123 enum logtypes type; /* Type of log channel */
124 FILE *fileptr; /* logfile logging file pointer */
125 char filename[256]; /* Filename */
126 AST_LIST_ENTRY(logchannel) list;
129 static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
137 enum logmsgtypes type;
144 AST_LIST_ENTRY(logmsg) list;
148 static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
149 static pthread_t logthread = AST_PTHREADT_NULL;
150 static ast_cond_t logcond;
151 static int close_logger_thread;
155 /*! \brief Logging channels used in the Asterisk logging system */
156 static char *levels[] = {
158 "---EVENT---", /* no longer used */
166 /*! \brief Colors used in the console for logging */
167 static int colors[] = {
177 AST_THREADSTORAGE(verbose_buf);
178 #define VERBOSE_BUF_INIT_SIZE 256
180 AST_THREADSTORAGE(log_buf);
181 #define LOG_BUF_INIT_SIZE 256
183 static int make_components(const char *s, int lineno)
187 char *stringp = ast_strdupa(s);
189 while ((w = strsep(&stringp, ","))) {
190 w = ast_skip_blanks(w);
191 if (!strcasecmp(w, "error"))
192 res |= (1 << __LOG_ERROR);
193 else if (!strcasecmp(w, "warning"))
194 res |= (1 << __LOG_WARNING);
195 else if (!strcasecmp(w, "notice"))
196 res |= (1 << __LOG_NOTICE);
197 else if (!strcasecmp(w, "debug"))
198 res |= (1 << __LOG_DEBUG);
199 else if (!strcasecmp(w, "verbose"))
200 res |= (1 << __LOG_VERBOSE);
201 else if (!strcasecmp(w, "dtmf"))
202 res |= (1 << __LOG_DTMF);
204 fprintf(stderr, "Logfile Warning: Unknown keyword '%s' at line %d of logger.conf\n", w, lineno);
211 static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno)
213 struct logchannel *chan;
219 if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan))))
222 if (!strcasecmp(channel, "console")) {
223 chan->type = LOGTYPE_CONSOLE;
224 } else if (!strncasecmp(channel, "syslog", 6)) {
227 * syslog.facility => level,level,level
229 facility = strchr(channel, '.');
230 if (!facility++ || !facility) {
236 * Walk through the list of facilitynames (defined in sys/syslog.h)
237 * to see if we can find the one we have been given
240 cptr = facilitynames;
241 while (cptr->c_name) {
242 if (!strcasecmp(facility, cptr->c_name)) {
243 chan->facility = cptr->c_val;
250 if (!strcasecmp(facility, "kern"))
251 chan->facility = LOG_KERN;
252 else if (!strcasecmp(facility, "USER"))
253 chan->facility = LOG_USER;
254 else if (!strcasecmp(facility, "MAIL"))
255 chan->facility = LOG_MAIL;
256 else if (!strcasecmp(facility, "DAEMON"))
257 chan->facility = LOG_DAEMON;
258 else if (!strcasecmp(facility, "AUTH"))
259 chan->facility = LOG_AUTH;
260 else if (!strcasecmp(facility, "SYSLOG"))
261 chan->facility = LOG_SYSLOG;
262 else if (!strcasecmp(facility, "LPR"))
263 chan->facility = LOG_LPR;
264 else if (!strcasecmp(facility, "NEWS"))
265 chan->facility = LOG_NEWS;
266 else if (!strcasecmp(facility, "UUCP"))
267 chan->facility = LOG_UUCP;
268 else if (!strcasecmp(facility, "CRON"))
269 chan->facility = LOG_CRON;
270 else if (!strcasecmp(facility, "LOCAL0"))
271 chan->facility = LOG_LOCAL0;
272 else if (!strcasecmp(facility, "LOCAL1"))
273 chan->facility = LOG_LOCAL1;
274 else if (!strcasecmp(facility, "LOCAL2"))
275 chan->facility = LOG_LOCAL2;
276 else if (!strcasecmp(facility, "LOCAL3"))
277 chan->facility = LOG_LOCAL3;
278 else if (!strcasecmp(facility, "LOCAL4"))
279 chan->facility = LOG_LOCAL4;
280 else if (!strcasecmp(facility, "LOCAL5"))
281 chan->facility = LOG_LOCAL5;
282 else if (!strcasecmp(facility, "LOCAL6"))
283 chan->facility = LOG_LOCAL6;
284 else if (!strcasecmp(facility, "LOCAL7"))
285 chan->facility = LOG_LOCAL7;
288 if (0 > chan->facility) {
289 fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
294 chan->type = LOGTYPE_SYSLOG;
295 snprintf(chan->filename, sizeof(chan->filename), "%s", channel);
296 openlog("asterisk", LOG_PID, chan->facility);
298 if (channel[0] == '/') {
299 if (!ast_strlen_zero(hostname)) {
300 snprintf(chan->filename, sizeof(chan->filename), "%s.%s", channel, hostname);
302 ast_copy_string(chan->filename, channel, sizeof(chan->filename));
306 if (!ast_strlen_zero(hostname)) {
307 snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s", ast_config_AST_LOG_DIR, channel, hostname);
309 snprintf(chan->filename, sizeof(chan->filename), "%s/%s", ast_config_AST_LOG_DIR, channel);
311 chan->fileptr = fopen(chan->filename, "a");
312 if (!chan->fileptr) {
313 /* Can't log here, since we're called with a lock */
314 fprintf(stderr, "Logger Warning: Unable to open log file '%s': %s\n", chan->filename, strerror(errno));
316 chan->type = LOGTYPE_FILE;
318 chan->logmask = make_components(components, lineno);
322 static void init_logger_chain(int locked)
324 struct logchannel *chan;
325 struct ast_config *cfg;
326 struct ast_variable *var;
328 struct ast_flags config_flags = { 0 };
330 if (!(cfg = ast_config_load2("logger.conf", "logger", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID)
333 /* delete our list of log channels */
335 AST_RWLIST_WRLOCK(&logchannels);
336 while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list)))
339 AST_RWLIST_UNLOCK(&logchannels);
346 /* If no config file, we're fine, set default options. */
349 fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
351 fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
352 if (!(chan = ast_calloc(1, sizeof(*chan))))
354 chan->type = LOGTYPE_CONSOLE;
355 chan->logmask = 28; /*warning,notice,error */
357 AST_RWLIST_WRLOCK(&logchannels);
358 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
360 AST_RWLIST_UNLOCK(&logchannels);
361 global_logmask |= chan->logmask;
365 if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
367 if (gethostname(hostname, sizeof(hostname) - 1)) {
368 ast_copy_string(hostname, "unknown", sizeof(hostname));
369 fprintf(stderr, "What box has no hostname???\n");
375 if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
376 ast_copy_string(dateformat, s, sizeof(dateformat));
378 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
379 if ((s = ast_variable_retrieve(cfg, "general", "queue_log")))
380 logfiles.queue_log = ast_true(s);
381 if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name")))
382 ast_copy_string(queue_log_name, s, sizeof(queue_log_name));
383 if ((s = ast_variable_retrieve(cfg, "general", "exec_after_rotate")))
384 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);
395 if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp"))) {
396 rotatestrategy = ast_true(s) ? TIMESTAMP : SEQUENTIAL;
397 fprintf(stderr, "rotatetimestamp option has been deprecated. Please use rotatestrategy instead.\n");
402 AST_RWLIST_WRLOCK(&logchannels);
403 var = ast_variable_browse(cfg, "logfiles");
404 for (; var; var = var->next) {
405 if (!(chan = make_logchannel(var->name, var->value, var->lineno)))
407 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
408 global_logmask |= chan->logmask;
411 AST_RWLIST_UNLOCK(&logchannels);
413 ast_config_destroy(cfg);
416 void ast_child_verbose(int level, const char *fmt, ...)
418 char *msg = NULL, *emsg = NULL, *sptr, *eptr;
422 /* Don't bother, if the level isn't that high */
423 if (option_verbose < level) {
429 if ((size = vsnprintf(msg, 0, fmt, ap)) < 0) {
436 if (!(msg = ast_malloc(size + 1))) {
441 vsnprintf(msg, size + 1, fmt, aq);
444 if (!(emsg = ast_malloc(size * 2 + 1))) {
449 for (sptr = msg, eptr = emsg; ; sptr++) {
460 fprintf(stdout, "verbose \"%s\" %d\n", emsg, level);
465 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
472 if (ast_check_realtime("queue_log")) {
474 vsnprintf(qlog_msg, sizeof(qlog_msg), fmt, ap);
476 snprintf(time_str, sizeof(time_str), "%ld", (long)time(NULL));
477 ast_store_realtime("queue_log", "time", time_str,
479 "queuename", queuename,
487 qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
488 vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
491 AST_RWLIST_RDLOCK(&logchannels);
493 fprintf(qlog, "%s\n", qlog_msg);
496 AST_RWLIST_UNLOCK(&logchannels);
500 static int rotate_file(const char *filename)
504 int x, y, which, found, res = 0, fd;
505 char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
507 switch (rotatestrategy) {
510 snprintf(new, sizeof(new), "%s.%d", filename, x);
511 fd = open(new, O_RDONLY);
517 if (rename(filename, new)) {
518 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
523 snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
524 if (rename(filename, new)) {
525 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
530 /* Find the next empty slot, including a possible suffix */
533 for (which = 0; which < ARRAY_LEN(suffixes); which++) {
534 snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
535 fd = open(new, O_RDONLY);
547 /* Found an empty slot */
548 for (y = x; y > 0; y--) {
549 for (which = 0; which < ARRAY_LEN(suffixes); which++) {
550 snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
551 fd = open(old, O_RDONLY);
553 /* Found the right suffix */
555 snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
556 if (rename(old, new)) {
557 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
565 /* Finally, rename the current file */
566 snprintf(new, sizeof(new), "%s.0", filename);
567 if (rename(filename, new)) {
568 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
573 if (!ast_strlen_zero(exec_after_rotate)) {
574 struct ast_channel *c = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Logger/rotate");
576 pbx_builtin_setvar_helper(c, "filename", filename);
577 pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
578 if (ast_safe_system(buf) != -1) {
579 ast_log(LOG_WARNING, "error executing '%s'\n", buf);
581 c = ast_channel_release(c);
586 static int reload_logger(int rotate)
588 char old[PATH_MAX] = "";
589 int queue_rotate = rotate;
590 struct logchannel *f;
594 AST_RWLIST_WRLOCK(&logchannels);
598 /* Check filesize - this one typically doesn't need an auto-rotate */
599 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
600 if (stat(old, &st) != 0 || st.st_size > 0x40000000) { /* Arbitrarily, 1 GB */
612 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
614 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
616 f->disabled = 0; /* Re-enable logging at reload */
617 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
619 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
620 fclose(f->fileptr); /* Close file */
623 rotate_file(f->filename);
627 filesize_reload_needed = 0;
629 init_logger_chain(1 /* locked */);
631 if (logfiles.queue_log) {
632 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
636 qlog = fopen(old, "a");
638 AST_RWLIST_UNLOCK(&logchannels);
639 ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
640 AST_RWLIST_WRLOCK(&logchannels);
641 ast_verb(1, "Asterisk Queue Logger restarted\n");
643 ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
648 AST_RWLIST_UNLOCK(&logchannels);
653 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
654 a full Asterisk reload) */
655 int logger_reload(void)
658 return RESULT_FAILURE;
659 return RESULT_SUCCESS;
662 static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
666 e->command = "logger reload";
668 "Usage: logger reload\n"
669 " Reloads the logger subsystem state. Use after restarting syslogd(8) if you are using syslog logging.\n";
674 if (reload_logger(0)) {
675 ast_cli(a->fd, "Failed to reload the logger\n");
681 static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
685 e->command = "logger rotate";
687 "Usage: logger rotate\n"
688 " Rotates and Reopens the log files.\n";
693 if (reload_logger(1)) {
694 ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
700 static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
708 e->command = "logger set level";
710 "Usage: logger set level\n"
711 " Set a specific log level to enabled/disabled for this console.\n";
718 return CLI_SHOWUSAGE;
720 for (x = 0; x <= NUMLOGLEVELS; x++) {
721 if (!strcasecmp(a->argv[3], levels[x])) {
727 state = ast_true(a->argv[4]) ? 1 : 0;
730 ast_console_toggle_loglevel(a->fd, level, state);
731 ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
733 return CLI_SHOWUSAGE;
738 /*! \brief CLI command to show logging system configuration */
739 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
741 #define FORMATL "%-35.35s %-8.8s %-9.9s "
742 struct logchannel *chan;
745 e->command = "logger show channels";
747 "Usage: logger show channels\n"
748 " List configured logger channels.\n";
753 ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
754 ast_cli(a->fd, "Configuration\n");
755 ast_cli(a->fd, FORMATL, "-------", "----", "------");
756 ast_cli(a->fd, "-------------\n");
757 AST_RWLIST_RDLOCK(&logchannels);
758 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
759 ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
760 chan->disabled ? "Disabled" : "Enabled");
761 ast_cli(a->fd, " - ");
762 if (chan->logmask & (1 << __LOG_DEBUG))
763 ast_cli(a->fd, "Debug ");
764 if (chan->logmask & (1 << __LOG_DTMF))
765 ast_cli(a->fd, "DTMF ");
766 if (chan->logmask & (1 << __LOG_VERBOSE))
767 ast_cli(a->fd, "Verbose ");
768 if (chan->logmask & (1 << __LOG_WARNING))
769 ast_cli(a->fd, "Warning ");
770 if (chan->logmask & (1 << __LOG_NOTICE))
771 ast_cli(a->fd, "Notice ");
772 if (chan->logmask & (1 << __LOG_ERROR))
773 ast_cli(a->fd, "Error ");
774 ast_cli(a->fd, "\n");
776 AST_RWLIST_UNLOCK(&logchannels);
777 ast_cli(a->fd, "\n");
783 void (*verboser)(const char *string);
784 AST_LIST_ENTRY(verb) list;
787 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
789 static struct ast_cli_entry cli_logger[] = {
790 AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
791 AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
792 AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
793 AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console")
796 static int handle_SIGXFSZ(int sig)
798 /* Indicate need to reload */
799 filesize_reload_needed = 1;
803 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, char *str, long pid)
807 if (level >= SYSLOG_NLEVELS) {
808 /* we are locked here, so cannot ast_log() */
809 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
813 if (level == __LOG_VERBOSE) {
814 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: %s", pid, str);
816 } else if (level == __LOG_DTMF) {
817 snprintf(buf, sizeof(buf), "DTMF[%ld]: %s", pid, str);
820 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: %s",
821 levels[level], pid, file, line, function, str);
824 term_strip(buf, buf, strlen(buf) + 1);
825 syslog(syslog_level_map[level], "%s", buf);
828 /*! \brief Print a normal log message to the channels */
829 static void logger_print_normal(struct logmsg *logmsg)
831 struct logchannel *chan = NULL;
834 AST_RWLIST_RDLOCK(&logchannels);
836 if (!AST_RWLIST_EMPTY(&logchannels)) {
837 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
838 /* If the channel is disabled, then move on to the next one */
841 /* Check syslog channels */
842 if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
843 ast_log_vsyslog(logmsg->level, logmsg->file, logmsg->line, logmsg->function, logmsg->str, logmsg->process_id);
844 /* Console channels */
845 } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
847 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
849 /* If the level is verbose, then skip it */
850 if (logmsg->level == __LOG_VERBOSE)
853 /* Turn the numerical line number into a string */
854 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
855 /* Build string to print out */
856 snprintf(buf, sizeof(buf), "[%s] %s[%ld]: %s:%s %s: %s",
858 term_color(tmp1, levels[logmsg->level], colors[logmsg->level], 0, sizeof(tmp1)),
860 term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
861 term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
862 term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
865 ast_console_puts_mutable(buf, logmsg->level);
867 } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
870 /* If no file pointer exists, skip it */
874 /* Print out to the file */
875 res = fprintf(chan->fileptr, "[%s] %s[%ld] %s: %s",
876 logmsg->date, levels[logmsg->level], logmsg->process_id, logmsg->file, logmsg->str);
877 if (res <= 0 && !ast_strlen_zero(logmsg->str)) {
878 fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
879 if (errno == ENOMEM || errno == ENOSPC)
880 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
882 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
883 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
885 } else if (res > 0) {
886 fflush(chan->fileptr);
890 } else if (logmsg->level != __LOG_VERBOSE) {
891 fputs(logmsg->str, stdout);
894 AST_RWLIST_UNLOCK(&logchannels);
896 /* If we need to reload because of the file size, then do so */
897 if (filesize_reload_needed) {
899 ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
905 /*! \brief Print a verbose message to the verbosers */
906 static void logger_print_verbose(struct logmsg *logmsg)
908 struct verb *v = NULL;
910 /* Iterate through the list of verbosers and pass them the log message string */
911 AST_RWLIST_RDLOCK(&verbosers);
912 AST_RWLIST_TRAVERSE(&verbosers, v, list)
913 v->verboser(logmsg->str);
914 AST_RWLIST_UNLOCK(&verbosers);
919 /*! \brief Actual logging thread */
920 static void *logger_thread(void *data)
922 struct logmsg *next = NULL, *msg = NULL;
925 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
926 AST_LIST_LOCK(&logmsgs);
927 if (AST_LIST_EMPTY(&logmsgs)) {
928 if (close_logger_thread) {
931 ast_cond_wait(&logcond, &logmsgs.lock);
934 next = AST_LIST_FIRST(&logmsgs);
935 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
936 AST_LIST_UNLOCK(&logmsgs);
938 /* Otherwise go through and process each message in the order added */
939 while ((msg = next)) {
940 /* Get the next entry now so that we can free our current structure later */
941 next = AST_LIST_NEXT(msg, list);
943 /* Depending on the type, send it to the proper function */
944 if (msg->type == LOGMSG_NORMAL)
945 logger_print_normal(msg);
946 else if (msg->type == LOGMSG_VERBOSE)
947 logger_print_verbose(msg);
949 /* Free the data since we are done */
953 /* If we should stop, then stop */
954 if (close_logger_thread)
961 int init_logger(void)
966 /* auto rotate if sig SIGXFSZ comes a-knockin */
967 (void) signal(SIGXFSZ, (void *) handle_SIGXFSZ);
969 /* start logger thread */
970 ast_cond_init(&logcond, NULL);
971 if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
972 ast_cond_destroy(&logcond);
976 /* register the logger cli commands */
977 ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
979 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
981 /* create log channels */
982 init_logger_chain(0 /* locked */);
984 if (logfiles.queue_log) {
985 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
986 qlog = fopen(tmp, "a");
987 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
992 void close_logger(void)
994 struct logchannel *f = NULL;
996 /* Stop logger thread */
997 AST_LIST_LOCK(&logmsgs);
998 close_logger_thread = 1;
999 ast_cond_signal(&logcond);
1000 AST_LIST_UNLOCK(&logmsgs);
1002 if (logthread != AST_PTHREADT_NULL)
1003 pthread_join(logthread, NULL);
1005 AST_RWLIST_WRLOCK(&logchannels);
1012 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
1013 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
1019 closelog(); /* syslog */
1021 AST_RWLIST_UNLOCK(&logchannels);
1027 * \brief send log messages to syslog and/or the console
1029 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
1031 struct logmsg *logmsg = NULL;
1032 struct ast_str *buf = NULL;
1034 struct timeval now = ast_tvnow();
1038 if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1041 if (AST_RWLIST_EMPTY(&logchannels)) {
1043 * we don't have the logger chain configured yet,
1044 * so just log to stdout
1046 if (level != __LOG_VERBOSE) {
1049 result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1051 if (result != AST_DYNSTR_BUILD_FAILED) {
1052 term_filter_escapes(ast_str_buffer(buf));
1053 fputs(ast_str_buffer(buf), stdout);
1059 /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
1060 are non-zero; LOG_DEBUG messages can still be displayed if option_debug
1061 is zero, if option_verbose is non-zero (this allows for 'level zero'
1062 LOG_DEBUG messages to be displayed, if the logmask on any channel
1065 if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
1068 /* Ignore anything that never gets logged anywhere */
1069 if (!(global_logmask & (1 << level)))
1074 res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1077 /* If the build failed, then abort and free this structure */
1078 if (res == AST_DYNSTR_BUILD_FAILED)
1081 /* Create a new logging message */
1082 if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1085 /* Copy string over */
1086 strcpy(logmsg->str, ast_str_buffer(buf));
1088 /* Set type to be normal */
1089 logmsg->type = LOGMSG_NORMAL;
1091 /* Create our date/time */
1092 ast_localtime(&now, &tm, NULL);
1093 ast_strftime(logmsg->date, sizeof(logmsg->date), dateformat, &tm);
1095 /* Copy over data */
1096 logmsg->level = level;
1097 logmsg->line = line;
1098 ast_copy_string(logmsg->file, file, sizeof(logmsg->file));
1099 ast_copy_string(logmsg->function, function, sizeof(logmsg->function));
1100 logmsg->process_id = (long) GETTID();
1102 /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1103 if (logthread != AST_PTHREADT_NULL) {
1104 AST_LIST_LOCK(&logmsgs);
1105 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1106 ast_cond_signal(&logcond);
1107 AST_LIST_UNLOCK(&logmsgs);
1109 logger_print_normal(logmsg);
1118 struct ast_bt *ast_bt_create(void)
1120 struct ast_bt *bt = ast_calloc(1, sizeof(*bt));
1122 ast_log(LOG_ERROR, "Unable to allocate memory for backtrace structure!\n");
1128 ast_bt_get_addresses(bt);
1133 int ast_bt_get_addresses(struct ast_bt *bt)
1135 bt->num_frames = backtrace(bt->addresses, AST_MAX_BT_FRAMES);
1140 void *ast_bt_destroy(struct ast_bt *bt)
1149 #endif /* HAVE_BKTR */
1151 void ast_backtrace(void)
1158 if (!(bt = ast_bt_create())) {
1159 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
1163 if ((strings = backtrace_symbols(bt->addresses, bt->num_frames))) {
1164 ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
1165 for (i = 0; i < bt->num_frames; i++) {
1166 ast_log(LOG_DEBUG, "#%d: [%p] %s\n", i, bt->addresses[i], strings[i]);
1170 ast_debug(1, "Could not allocate memory for backtrace\n");
1174 ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1178 void __ast_verbose_ap(const char *file, int line, const char *func, const char *fmt, va_list ap)
1180 struct logmsg *logmsg = NULL;
1181 struct ast_str *buf = NULL;
1184 if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
1187 if (ast_opt_timestamp) {
1194 ast_localtime(&now, &tm, NULL);
1195 ast_strftime(date, sizeof(date), dateformat, &tm);
1196 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1197 sprintf(datefmt, "%c[%s] %s", 127, date, fmt);
1200 char *tmp = alloca(strlen(fmt) + 2);
1201 sprintf(tmp, "%c%s", 127, fmt);
1206 res = ast_str_set_va(&buf, 0, fmt, ap);
1208 /* If the build failed then we can drop this allocated message */
1209 if (res == AST_DYNSTR_BUILD_FAILED)
1212 if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1215 strcpy(logmsg->str, ast_str_buffer(buf));
1217 ast_log(__LOG_VERBOSE, file, line, func, "%s", logmsg->str + 1);
1220 logmsg->type = LOGMSG_VERBOSE;
1222 /* Add to the list and poke the thread if possible */
1223 if (logthread != AST_PTHREADT_NULL) {
1224 AST_LIST_LOCK(&logmsgs);
1225 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1226 ast_cond_signal(&logcond);
1227 AST_LIST_UNLOCK(&logmsgs);
1229 logger_print_verbose(logmsg);
1234 void __ast_verbose(const char *file, int line, const char *func, const char *fmt, ...)
1238 __ast_verbose_ap(file, line, func, fmt, ap);
1242 /* No new code should use this directly, but we have the ABI for backwards compat */
1244 void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
1245 void ast_verbose(const char *fmt, ...)
1249 __ast_verbose_ap("", 0, "", fmt, ap);
1253 int ast_register_verbose(void (*v)(const char *string))
1257 if (!(verb = ast_malloc(sizeof(*verb))))
1262 AST_RWLIST_WRLOCK(&verbosers);
1263 AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1264 AST_RWLIST_UNLOCK(&verbosers);
1269 int ast_unregister_verbose(void (*v)(const char *string))
1273 AST_RWLIST_WRLOCK(&verbosers);
1274 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1275 if (cur->verboser == v) {
1276 AST_RWLIST_REMOVE_CURRENT(list);
1281 AST_RWLIST_TRAVERSE_SAFE_END;
1282 AST_RWLIST_UNLOCK(&verbosers);
1284 return cur ? 0 : -1;