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$")
38 #include "asterisk/_private.h"
39 #include "asterisk/paths.h" /* use ast_config_AST_LOG_DIR */
46 #define MAX_BACKTRACE_FRAMES 20
49 #define SYSLOG_NAMES /* so we can map syslog facilities names to their numeric values,
50 from <syslog.h> which is included by logger.h */
53 static int syslog_level_map[] = {
55 LOG_INFO, /* arbitrary equivalent of LOG_EVENT */
63 #define SYSLOG_NLEVELS sizeof(syslog_level_map) / sizeof(int)
65 #undef _ASTERISK_LOGGER_H /* now include logger.h */
66 #include "asterisk/logger.h"
67 #include "asterisk/lock.h"
68 #include "asterisk/channel.h"
69 #include "asterisk/config.h"
70 #include "asterisk/term.h"
71 #include "asterisk/cli.h"
72 #include "asterisk/utils.h"
73 #include "asterisk/manager.h"
74 #include "asterisk/threadstorage.h"
75 #include "asterisk/strings.h"
76 #include "asterisk/pbx.h"
78 #if defined(__linux__) && !defined(__NR_gettid)
79 #include <asm/unistd.h>
82 #if defined(__linux__) && defined(__NR_gettid)
83 #define GETTID() syscall(__NR_gettid)
85 #define GETTID() getpid()
88 static char dateformat[256] = "%b %e %T"; /* Original Asterisk Format */
90 static char queue_log_name[256] = QUEUELOG;
91 static char exec_after_rotate[256] = "";
93 static int filesize_reload_needed;
94 static int global_logmask = -1;
97 SEQUENTIAL = 1 << 0, /* Original method - create a new file, in order */
98 ROTATE = 1 << 1, /* Rotate all files, such that the oldest file has the highest suffix */
99 TIMESTAMP = 1 << 2, /* Append the epoch timestamp onto the end of the archived file */
100 } rotatestrategy = SEQUENTIAL;
103 unsigned int queue_log:1;
104 unsigned int event_log:1;
105 } logfiles = { 1, 1 };
107 static char hostname[MAXHOSTNAMELEN];
116 int logmask; /* What to log to this channel */
117 int disabled; /* If this channel is disabled or not */
118 int facility; /* syslog facility */
119 enum logtypes type; /* Type of log channel */
120 FILE *fileptr; /* logfile logging file pointer */
121 char filename[256]; /* Filename */
122 AST_LIST_ENTRY(logchannel) list;
125 static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
133 enum logmsgtypes type;
140 AST_LIST_ENTRY(logmsg) list;
144 static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
145 static pthread_t logthread = AST_PTHREADT_NULL;
146 static ast_cond_t logcond;
147 static int close_logger_thread;
149 static FILE *eventlog;
152 /*! \brief Logging channels used in the Asterisk logging system */
153 static char *levels[] = {
163 /*! \brief Colors used in the console for logging */
164 static int colors[] = {
174 AST_THREADSTORAGE(verbose_buf);
175 #define VERBOSE_BUF_INIT_SIZE 256
177 AST_THREADSTORAGE(log_buf);
178 #define LOG_BUF_INIT_SIZE 256
180 static int make_components(const char *s, int lineno)
184 char *stringp = ast_strdupa(s);
186 while ((w = strsep(&stringp, ","))) {
187 w = ast_skip_blanks(w);
188 if (!strcasecmp(w, "error"))
189 res |= (1 << __LOG_ERROR);
190 else if (!strcasecmp(w, "warning"))
191 res |= (1 << __LOG_WARNING);
192 else if (!strcasecmp(w, "notice"))
193 res |= (1 << __LOG_NOTICE);
194 else if (!strcasecmp(w, "event"))
195 res |= (1 << __LOG_EVENT);
196 else if (!strcasecmp(w, "debug"))
197 res |= (1 << __LOG_DEBUG);
198 else if (!strcasecmp(w, "verbose"))
199 res |= (1 << __LOG_VERBOSE);
200 else if (!strcasecmp(w, "dtmf"))
201 res |= (1 << __LOG_DTMF);
203 fprintf(stderr, "Logfile Warning: Unknown keyword '%s' at line %d of logger.conf\n", w, lineno);
210 static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno)
212 struct logchannel *chan;
218 if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan))))
221 if (!strcasecmp(channel, "console")) {
222 chan->type = LOGTYPE_CONSOLE;
223 } else if (!strncasecmp(channel, "syslog", 6)) {
226 * syslog.facility => level,level,level
228 facility = strchr(channel, '.');
229 if (!facility++ || !facility) {
235 * Walk through the list of facilitynames (defined in sys/syslog.h)
236 * to see if we can find the one we have been given
239 cptr = facilitynames;
240 while (cptr->c_name) {
241 if (!strcasecmp(facility, cptr->c_name)) {
242 chan->facility = cptr->c_val;
249 if (!strcasecmp(facility, "kern"))
250 chan->facility = LOG_KERN;
251 else if (!strcasecmp(facility, "USER"))
252 chan->facility = LOG_USER;
253 else if (!strcasecmp(facility, "MAIL"))
254 chan->facility = LOG_MAIL;
255 else if (!strcasecmp(facility, "DAEMON"))
256 chan->facility = LOG_DAEMON;
257 else if (!strcasecmp(facility, "AUTH"))
258 chan->facility = LOG_AUTH;
259 else if (!strcasecmp(facility, "SYSLOG"))
260 chan->facility = LOG_SYSLOG;
261 else if (!strcasecmp(facility, "LPR"))
262 chan->facility = LOG_LPR;
263 else if (!strcasecmp(facility, "NEWS"))
264 chan->facility = LOG_NEWS;
265 else if (!strcasecmp(facility, "UUCP"))
266 chan->facility = LOG_UUCP;
267 else if (!strcasecmp(facility, "CRON"))
268 chan->facility = LOG_CRON;
269 else if (!strcasecmp(facility, "LOCAL0"))
270 chan->facility = LOG_LOCAL0;
271 else if (!strcasecmp(facility, "LOCAL1"))
272 chan->facility = LOG_LOCAL1;
273 else if (!strcasecmp(facility, "LOCAL2"))
274 chan->facility = LOG_LOCAL2;
275 else if (!strcasecmp(facility, "LOCAL3"))
276 chan->facility = LOG_LOCAL3;
277 else if (!strcasecmp(facility, "LOCAL4"))
278 chan->facility = LOG_LOCAL4;
279 else if (!strcasecmp(facility, "LOCAL5"))
280 chan->facility = LOG_LOCAL5;
281 else if (!strcasecmp(facility, "LOCAL6"))
282 chan->facility = LOG_LOCAL6;
283 else if (!strcasecmp(facility, "LOCAL7"))
284 chan->facility = LOG_LOCAL7;
287 if (0 > chan->facility) {
288 fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
293 chan->type = LOGTYPE_SYSLOG;
294 snprintf(chan->filename, sizeof(chan->filename), "%s", channel);
295 openlog("asterisk", LOG_PID, chan->facility);
297 if (channel[0] == '/') {
298 if (!ast_strlen_zero(hostname)) {
299 snprintf(chan->filename, sizeof(chan->filename), "%s.%s", channel, hostname);
301 ast_copy_string(chan->filename, channel, sizeof(chan->filename));
305 if (!ast_strlen_zero(hostname)) {
306 snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s", ast_config_AST_LOG_DIR, channel, hostname);
308 snprintf(chan->filename, sizeof(chan->filename), "%s/%s", ast_config_AST_LOG_DIR, channel);
310 chan->fileptr = fopen(chan->filename, "a");
311 if (!chan->fileptr) {
312 /* Can't log here, since we're called with a lock */
313 fprintf(stderr, "Logger Warning: Unable to open log file '%s': %s\n", chan->filename, strerror(errno));
315 chan->type = LOGTYPE_FILE;
317 chan->logmask = make_components(components, lineno);
321 static void init_logger_chain(int locked)
323 struct logchannel *chan;
324 struct ast_config *cfg;
325 struct ast_variable *var;
327 struct ast_flags config_flags = { 0 };
329 if (!(cfg = ast_config_load2("logger.conf", "logger", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID)
332 /* delete our list of log channels */
334 AST_RWLIST_WRLOCK(&logchannels);
335 while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list)))
338 AST_RWLIST_UNLOCK(&logchannels);
345 /* If no config file, we're fine, set default options. */
348 fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
350 fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
351 if (!(chan = ast_calloc(1, sizeof(*chan))))
353 chan->type = LOGTYPE_CONSOLE;
354 chan->logmask = 28; /*warning,notice,error */
356 AST_RWLIST_WRLOCK(&logchannels);
357 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
359 AST_RWLIST_UNLOCK(&logchannels);
360 global_logmask |= chan->logmask;
364 if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
366 if (gethostname(hostname, sizeof(hostname) - 1)) {
367 ast_copy_string(hostname, "unknown", sizeof(hostname));
368 fprintf(stderr, "What box has no hostname???\n");
374 if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
375 ast_copy_string(dateformat, s, sizeof(dateformat));
377 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
378 if ((s = ast_variable_retrieve(cfg, "general", "queue_log")))
379 logfiles.queue_log = ast_true(s);
380 if ((s = ast_variable_retrieve(cfg, "general", "event_log")))
381 logfiles.event_log = ast_true(s);
382 if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name")))
383 ast_copy_string(queue_log_name, s, sizeof(queue_log_name));
384 if ((s = ast_variable_retrieve(cfg, "general", "exec_after_rotate")))
385 ast_copy_string(exec_after_rotate, s, sizeof(exec_after_rotate));
386 if ((s = ast_variable_retrieve(cfg, "general", "rotatestrategy"))) {
387 if (strcasecmp(s, "timestamp") == 0)
388 rotatestrategy = TIMESTAMP;
389 else if (strcasecmp(s, "rotate") == 0)
390 rotatestrategy = ROTATE;
391 else if (strcasecmp(s, "sequential") == 0)
392 rotatestrategy = SEQUENTIAL;
394 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);
404 var = ast_variable_browse(cfg, "logfiles");
405 for (; var; var = var->next) {
406 if (!(chan = make_logchannel(var->name, var->value, var->lineno)))
408 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
409 global_logmask |= chan->logmask;
412 AST_RWLIST_UNLOCK(&logchannels);
414 ast_config_destroy(cfg);
417 void ast_child_verbose(int level, const char *fmt, ...)
419 char *msg = NULL, *emsg = NULL, *sptr, *eptr;
423 /* Don't bother, if the level isn't that high */
424 if (option_verbose < level) {
430 if ((size = vsnprintf(msg, 0, fmt, ap)) < 0) {
437 if (!(msg = ast_malloc(size + 1))) {
442 vsnprintf(msg, size + 1, fmt, aq);
445 if (!(emsg = ast_malloc(size * 2 + 1))) {
450 for (sptr = msg, eptr = emsg; ; sptr++) {
461 fprintf(stdout, "verbose \"%s\" %d\n", emsg, level);
466 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
473 if (ast_check_realtime("queue_log")) {
475 vsnprintf(qlog_msg, sizeof(qlog_msg), fmt, ap);
477 snprintf(time_str, sizeof(time_str), "%ld", (long)time(NULL));
478 ast_store_realtime("queue_log", "time", time_str,
480 "queuename", queuename,
488 qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
489 vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
492 AST_RWLIST_RDLOCK(&logchannels);
494 fprintf(qlog, "%s\n", qlog_msg);
497 AST_RWLIST_UNLOCK(&logchannels);
501 static int rotate_file(const char *filename)
505 int x, y, which, found, res = 0, fd;
506 char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
508 switch (rotatestrategy) {
511 snprintf(new, sizeof(new), "%s.%d", filename, x);
512 fd = open(new, O_RDONLY);
518 if (rename(filename, new)) {
519 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
524 snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
525 if (rename(filename, new)) {
526 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
531 /* Find the next empty slot, including a possible suffix */
534 for (which = 0; which < ARRAY_LEN(suffixes); which++) {
535 snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
536 fd = open(new, O_RDONLY);
548 /* Found an empty slot */
549 for (y = x; y > 0; y--) {
550 for (which = 0; which < ARRAY_LEN(suffixes); which++) {
551 snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
552 fd = open(old, O_RDONLY);
554 /* Found the right suffix */
556 snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
557 if (rename(old, new)) {
558 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
566 /* Finally, rename the current file */
567 snprintf(new, sizeof(new), "%s.0", filename);
568 if (rename(filename, new)) {
569 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
574 if (!ast_strlen_zero(exec_after_rotate)) {
575 struct ast_channel *c = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Logger/rotate");
577 pbx_builtin_setvar_helper(c, "filename", filename);
578 pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
579 if (system(buf) < 0) {
580 ast_log(LOG_WARNING, "system() failed for '%s': %s\n", buf, strerror(errno));
587 static int reload_logger(int rotate)
589 char old[PATH_MAX] = "";
590 int event_rotate = rotate, queue_rotate = rotate;
591 struct logchannel *f;
595 AST_RWLIST_WRLOCK(&logchannels);
599 /* Check filesize - this one typically doesn't need an auto-rotate */
600 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
601 if (stat(old, &st) != 0 || st.st_size > 0x40000000) { /* Arbitrarily, 1 GB */
615 /* Check filesize - this one typically doesn't need an auto-rotate */
616 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
617 if (stat(old, &st) != 0 || st.st_size > 0x40000000) { /* Arbitrarily, 1 GB */
630 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
632 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
634 f->disabled = 0; /* Re-enable logging at reload */
635 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
637 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
638 fclose(f->fileptr); /* Close file */
641 rotate_file(f->filename);
645 filesize_reload_needed = 0;
647 init_logger_chain(1 /* locked */);
649 if (logfiles.event_log) {
650 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
654 eventlog = fopen(old, "a");
656 ast_log(LOG_EVENT, "Restarted Asterisk Event Logger\n");
657 ast_verb(1, "Asterisk Event Logger restarted\n");
659 ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
664 if (logfiles.queue_log) {
665 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
669 qlog = fopen(old, "a");
671 AST_RWLIST_UNLOCK(&logchannels);
672 ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
673 AST_RWLIST_WRLOCK(&logchannels);
674 ast_log(LOG_EVENT, "Restarted Asterisk Queue Logger\n");
675 ast_verb(1, "Asterisk Queue Logger restarted\n");
677 ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
682 AST_RWLIST_UNLOCK(&logchannels);
687 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
688 a full Asterisk reload) */
689 int logger_reload(void)
692 return RESULT_FAILURE;
693 return RESULT_SUCCESS;
696 static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
700 e->command = "logger reload";
702 "Usage: logger reload\n"
703 " Reloads the logger subsystem state. Use after restarting syslogd(8) if you are using syslog logging.\n";
708 if (reload_logger(0)) {
709 ast_cli(a->fd, "Failed to reload the logger\n");
715 static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
719 e->command = "logger rotate";
721 "Usage: logger rotate\n"
722 " Rotates and Reopens the log files.\n";
727 if (reload_logger(1)) {
728 ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
734 static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
742 e->command = "logger set level";
744 "Usage: logger set level\n"
745 " Set a specific log level to enabled/disabled for this console.\n";
752 return CLI_SHOWUSAGE;
754 for (x = 0; x <= NUMLOGLEVELS; x++) {
755 if (!strcasecmp(a->argv[3], levels[x])) {
761 state = ast_true(a->argv[4]) ? 1 : 0;
764 ast_console_toggle_loglevel(a->fd, level, state);
765 ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
767 return CLI_SHOWUSAGE;
772 /*! \brief CLI command to show logging system configuration */
773 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
775 #define FORMATL "%-35.35s %-8.8s %-9.9s "
776 struct logchannel *chan;
779 e->command = "logger show channels";
781 "Usage: logger show channels\n"
782 " List configured logger channels.\n";
787 ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
788 ast_cli(a->fd, "Configuration\n");
789 ast_cli(a->fd, FORMATL, "-------", "----", "------");
790 ast_cli(a->fd, "-------------\n");
791 AST_RWLIST_RDLOCK(&logchannels);
792 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
793 ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
794 chan->disabled ? "Disabled" : "Enabled");
795 ast_cli(a->fd, " - ");
796 if (chan->logmask & (1 << __LOG_DEBUG))
797 ast_cli(a->fd, "Debug ");
798 if (chan->logmask & (1 << __LOG_DTMF))
799 ast_cli(a->fd, "DTMF ");
800 if (chan->logmask & (1 << __LOG_VERBOSE))
801 ast_cli(a->fd, "Verbose ");
802 if (chan->logmask & (1 << __LOG_WARNING))
803 ast_cli(a->fd, "Warning ");
804 if (chan->logmask & (1 << __LOG_NOTICE))
805 ast_cli(a->fd, "Notice ");
806 if (chan->logmask & (1 << __LOG_ERROR))
807 ast_cli(a->fd, "Error ");
808 if (chan->logmask & (1 << __LOG_EVENT))
809 ast_cli(a->fd, "Event ");
810 ast_cli(a->fd, "\n");
812 AST_RWLIST_UNLOCK(&logchannels);
813 ast_cli(a->fd, "\n");
819 void (*verboser)(const char *string);
820 AST_LIST_ENTRY(verb) list;
823 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
825 static struct ast_cli_entry cli_logger[] = {
826 AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
827 AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
828 AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
829 AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console")
832 static int handle_SIGXFSZ(int sig)
834 /* Indicate need to reload */
835 filesize_reload_needed = 1;
839 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, char *str, long pid)
843 if (level >= SYSLOG_NLEVELS) {
844 /* we are locked here, so cannot ast_log() */
845 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
849 if (level == __LOG_VERBOSE) {
850 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: %s", pid, str);
852 } else if (level == __LOG_DTMF) {
853 snprintf(buf, sizeof(buf), "DTMF[%ld]: %s", pid, str);
856 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: %s",
857 levels[level], pid, file, line, function, str);
860 term_strip(buf, buf, strlen(buf) + 1);
861 syslog(syslog_level_map[level], "%s", buf);
864 /*! \brief Print a normal log message to the channels */
865 static void logger_print_normal(struct logmsg *logmsg)
867 struct logchannel *chan = NULL;
870 AST_RWLIST_RDLOCK(&logchannels);
872 if (logfiles.event_log && logmsg->level == __LOG_EVENT) {
873 fprintf(eventlog, "%s asterisk[%ld]: %s", logmsg->date, (long)getpid(), logmsg->str);
875 AST_RWLIST_UNLOCK(&logchannels);
879 if (!AST_RWLIST_EMPTY(&logchannels)) {
880 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
881 /* If the channel is disabled, then move on to the next one */
884 /* Check syslog channels */
885 if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
886 ast_log_vsyslog(logmsg->level, logmsg->file, logmsg->line, logmsg->function, logmsg->str, logmsg->process_id);
887 /* Console channels */
888 } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
890 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
892 /* If the level is verbose, then skip it */
893 if (logmsg->level == __LOG_VERBOSE)
896 /* Turn the numerical line number into a string */
897 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
898 /* Build string to print out */
899 snprintf(buf, sizeof(buf), "[%s] %s[%ld]: %s:%s %s: %s",
901 term_color(tmp1, levels[logmsg->level], colors[logmsg->level], 0, sizeof(tmp1)),
903 term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
904 term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
905 term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
908 ast_console_puts_mutable(buf, logmsg->level);
910 } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
913 /* If no file pointer exists, skip it */
917 /* Print out to the file */
918 res = fprintf(chan->fileptr, "[%s] %s[%ld] %s: %s",
919 logmsg->date, levels[logmsg->level], logmsg->process_id, logmsg->file, logmsg->str);
920 if (res <= 0 && !ast_strlen_zero(logmsg->str)) {
921 fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
922 if (errno == ENOMEM || errno == ENOSPC)
923 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
925 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
926 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
928 } else if (res > 0) {
929 fflush(chan->fileptr);
933 } else if (logmsg->level != __LOG_VERBOSE) {
934 fputs(logmsg->str, stdout);
937 AST_RWLIST_UNLOCK(&logchannels);
939 /* If we need to reload because of the file size, then do so */
940 if (filesize_reload_needed) {
942 ast_log(LOG_EVENT, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
943 ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
949 /*! \brief Print a verbose message to the verbosers */
950 static void logger_print_verbose(struct logmsg *logmsg)
952 struct verb *v = NULL;
954 /* Iterate through the list of verbosers and pass them the log message string */
955 AST_RWLIST_RDLOCK(&verbosers);
956 AST_RWLIST_TRAVERSE(&verbosers, v, list)
957 v->verboser(logmsg->str);
958 AST_RWLIST_UNLOCK(&verbosers);
963 /*! \brief Actual logging thread */
964 static void *logger_thread(void *data)
966 struct logmsg *next = NULL, *msg = NULL;
969 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
970 AST_LIST_LOCK(&logmsgs);
971 if (AST_LIST_EMPTY(&logmsgs))
972 ast_cond_wait(&logcond, &logmsgs.lock);
973 next = AST_LIST_FIRST(&logmsgs);
974 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
975 AST_LIST_UNLOCK(&logmsgs);
977 /* Otherwise go through and process each message in the order added */
978 while ((msg = next)) {
979 /* Get the next entry now so that we can free our current structure later */
980 next = AST_LIST_NEXT(msg, list);
982 /* Depending on the type, send it to the proper function */
983 if (msg->type == LOGMSG_NORMAL)
984 logger_print_normal(msg);
985 else if (msg->type == LOGMSG_VERBOSE)
986 logger_print_verbose(msg);
988 /* Free the data since we are done */
992 /* If we should stop, then stop */
993 if (close_logger_thread)
1000 int init_logger(void)
1005 /* auto rotate if sig SIGXFSZ comes a-knockin */
1006 (void) signal(SIGXFSZ, (void *) handle_SIGXFSZ);
1008 /* start logger thread */
1009 ast_cond_init(&logcond, NULL);
1010 if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
1011 ast_cond_destroy(&logcond);
1015 /* register the logger cli commands */
1016 ast_cli_register_multiple(cli_logger, sizeof(cli_logger) / sizeof(struct ast_cli_entry));
1018 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
1020 /* create log channels */
1021 init_logger_chain(0 /* locked */);
1023 /* create the eventlog */
1024 if (logfiles.event_log) {
1025 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
1026 eventlog = fopen(tmp, "a");
1028 ast_log(LOG_EVENT, "Started Asterisk Event Logger\n");
1029 ast_verb(1, "Asterisk Event Logger Started %s\n", tmp);
1031 ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
1036 if (logfiles.queue_log) {
1037 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
1038 qlog = fopen(tmp, "a");
1039 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
1044 void close_logger(void)
1046 struct logchannel *f = NULL;
1048 /* Stop logger thread */
1049 AST_LIST_LOCK(&logmsgs);
1050 close_logger_thread = 1;
1051 ast_cond_signal(&logcond);
1052 AST_LIST_UNLOCK(&logmsgs);
1054 if (logthread != AST_PTHREADT_NULL)
1055 pthread_join(logthread, NULL);
1057 AST_RWLIST_WRLOCK(&logchannels);
1069 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
1070 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
1076 closelog(); /* syslog */
1078 AST_RWLIST_UNLOCK(&logchannels);
1084 * \brief send log messages to syslog and/or the console
1086 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
1088 struct logmsg *logmsg = NULL;
1089 struct ast_str *buf = NULL;
1091 struct timeval now = ast_tvnow();
1095 if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1098 if (AST_RWLIST_EMPTY(&logchannels)) {
1100 * we don't have the logger chain configured yet,
1101 * so just log to stdout
1103 if (level != __LOG_VERBOSE) {
1106 result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1108 if (result != AST_DYNSTR_BUILD_FAILED) {
1109 term_filter_escapes(buf->str);
1110 fputs(buf->str, stdout);
1116 /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
1117 are non-zero; LOG_DEBUG messages can still be displayed if option_debug
1118 is zero, if option_verbose is non-zero (this allows for 'level zero'
1119 LOG_DEBUG messages to be displayed, if the logmask on any channel
1122 if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
1125 /* Ignore anything that never gets logged anywhere */
1126 if (!(global_logmask & (1 << level)))
1131 res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1134 /* If the build failed, then abort and free this structure */
1135 if (res == AST_DYNSTR_BUILD_FAILED)
1138 /* Create a new logging message */
1139 if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1142 /* Copy string over */
1143 strcpy(logmsg->str, buf->str);
1145 /* Set type to be normal */
1146 logmsg->type = LOGMSG_NORMAL;
1148 /* Create our date/time */
1149 ast_localtime(&now, &tm, NULL);
1150 ast_strftime(logmsg->date, sizeof(logmsg->date), dateformat, &tm);
1152 /* Copy over data */
1153 logmsg->level = level;
1154 logmsg->line = line;
1155 ast_copy_string(logmsg->file, file, sizeof(logmsg->file));
1156 ast_copy_string(logmsg->function, function, sizeof(logmsg->function));
1157 logmsg->process_id = (long) GETTID();
1159 /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1160 if (logthread != AST_PTHREADT_NULL) {
1161 AST_LIST_LOCK(&logmsgs);
1162 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1163 ast_cond_signal(&logcond);
1164 AST_LIST_UNLOCK(&logmsgs);
1166 logger_print_normal(logmsg);
1175 struct ast_bt *ast_bt_create(void)
1177 struct ast_bt *bt = ast_calloc(1, sizeof(*bt));
1179 ast_log(LOG_ERROR, "Unable to allocate memory for backtrace structure!\n");
1185 ast_bt_get_addresses(bt);
1190 int ast_bt_get_addresses(struct ast_bt *bt)
1192 bt->num_frames = backtrace(bt->addresses, AST_MAX_BT_FRAMES);
1197 void *ast_bt_destroy(struct ast_bt *bt)
1206 #endif /* HAVE_BKTR */
1208 void ast_backtrace(void)
1215 if (!(bt = ast_bt_create())) {
1216 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
1220 if ((strings = backtrace_symbols(bt->addresses, bt->num_frames))) {
1221 ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
1222 for (i = 0; i < bt->num_frames; i++) {
1223 ast_log(LOG_DEBUG, "#%d: [%p] %s\n", i, bt->addresses[i], strings[i]);
1227 ast_debug(1, "Could not allocate memory for backtrace\n");
1231 ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1235 void __ast_verbose_ap(const char *file, int line, const char *func, const char *fmt, va_list ap)
1237 struct logmsg *logmsg = NULL;
1238 struct ast_str *buf = NULL;
1241 if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
1244 if (ast_opt_timestamp) {
1251 ast_localtime(&now, &tm, NULL);
1252 ast_strftime(date, sizeof(date), dateformat, &tm);
1253 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1254 sprintf(datefmt, "%c[%s] %s", 127, date, fmt);
1257 char *tmp = alloca(strlen(fmt) + 2);
1258 sprintf(tmp, "%c%s", 127, fmt);
1263 res = ast_str_set_va(&buf, 0, fmt, ap);
1265 /* If the build failed then we can drop this allocated message */
1266 if (res == AST_DYNSTR_BUILD_FAILED)
1269 if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1272 strcpy(logmsg->str, buf->str);
1274 ast_log(__LOG_VERBOSE, file, line, func, "%s", logmsg->str + 1);
1277 logmsg->type = LOGMSG_VERBOSE;
1279 /* Add to the list and poke the thread if possible */
1280 if (logthread != AST_PTHREADT_NULL) {
1281 AST_LIST_LOCK(&logmsgs);
1282 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1283 ast_cond_signal(&logcond);
1284 AST_LIST_UNLOCK(&logmsgs);
1286 logger_print_verbose(logmsg);
1291 void __ast_verbose(const char *file, int line, const char *func, const char *fmt, ...)
1295 __ast_verbose_ap(file, line, func, fmt, ap);
1299 /* No new code should use this directly, but we have the ABI for backwards compat */
1301 void ast_verbose(const char *fmt, ...) __attribute__ ((format (printf, 1, 2)));
1302 void ast_verbose(const char *fmt, ...)
1306 __ast_verbose_ap("", 0, "", fmt, ap);
1310 int ast_register_verbose(void (*v)(const char *string))
1314 if (!(verb = ast_malloc(sizeof(*verb))))
1319 AST_RWLIST_WRLOCK(&verbosers);
1320 AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1321 AST_RWLIST_UNLOCK(&verbosers);
1326 int ast_unregister_verbose(void (*v)(const char *string))
1330 AST_RWLIST_WRLOCK(&verbosers);
1331 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1332 if (cur->verboser == v) {
1333 AST_RWLIST_REMOVE_CURRENT(list);
1338 AST_RWLIST_TRAVERSE_SAFE_END;
1339 AST_RWLIST_UNLOCK(&verbosers);
1341 return cur ? 0 : -1;