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$")
40 #include <sys/types.h>
43 #if ((defined(AST_DEVMODE)) && (defined(linux)))
45 #define MAX_BACKTRACE_FRAMES 20
48 #define SYSLOG_NAMES /* so we can map syslog facilities names to their numeric values,
49 from <syslog.h> which is included by logger.h */
52 static int syslog_level_map[] = {
54 LOG_INFO, /* arbitrary equivalent of LOG_EVENT */
62 #define SYSLOG_NLEVELS sizeof(syslog_level_map) / sizeof(int)
64 #include "asterisk/logger.h"
65 #include "asterisk/lock.h"
66 #include "asterisk/options.h"
67 #include "asterisk/channel.h"
68 #include "asterisk/config.h"
69 #include "asterisk/term.h"
70 #include "asterisk/cli.h"
71 #include "asterisk/utils.h"
72 #include "asterisk/manager.h"
73 #include "asterisk/threadstorage.h"
74 #include "asterisk/strings.h"
75 #include "asterisk/channel.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;
138 const char *function;
139 AST_LIST_ENTRY(logmsg) list;
143 static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
144 static pthread_t logthread = AST_PTHREADT_NULL;
145 static ast_cond_t logcond;
146 static int close_logger_thread;
148 static FILE *eventlog;
151 static char *levels[] = {
161 static int colors[] = {
171 AST_THREADSTORAGE(verbose_buf);
172 #define VERBOSE_BUF_INIT_SIZE 256
174 AST_THREADSTORAGE(log_buf);
175 #define LOG_BUF_INIT_SIZE 256
177 static int make_components(char *s, int lineno)
183 while ((w = strsep(&stringp, ","))) {
184 w = ast_skip_blanks(w);
185 if (!strcasecmp(w, "error"))
186 res |= (1 << __LOG_ERROR);
187 else if (!strcasecmp(w, "warning"))
188 res |= (1 << __LOG_WARNING);
189 else if (!strcasecmp(w, "notice"))
190 res |= (1 << __LOG_NOTICE);
191 else if (!strcasecmp(w, "event"))
192 res |= (1 << __LOG_EVENT);
193 else if (!strcasecmp(w, "debug"))
194 res |= (1 << __LOG_DEBUG);
195 else if (!strcasecmp(w, "verbose"))
196 res |= (1 << __LOG_VERBOSE);
197 else if (!strcasecmp(w, "dtmf"))
198 res |= (1 << __LOG_DTMF);
200 fprintf(stderr, "Logfile Warning: Unknown keyword '%s' at line %d of logger.conf\n", w, lineno);
207 static struct logchannel *make_logchannel(char *channel, char *components, int lineno)
209 struct logchannel *chan;
215 if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan))))
218 if (!strcasecmp(channel, "console")) {
219 chan->type = LOGTYPE_CONSOLE;
220 } else if (!strncasecmp(channel, "syslog", 6)) {
223 * syslog.facility => level,level,level
225 facility = strchr(channel, '.');
226 if (!facility++ || !facility) {
232 * Walk through the list of facilitynames (defined in sys/syslog.h)
233 * to see if we can find the one we have been given
236 cptr = facilitynames;
237 while (cptr->c_name) {
238 if (!strcasecmp(facility, cptr->c_name)) {
239 chan->facility = cptr->c_val;
246 if (!strcasecmp(facility, "kern"))
247 chan->facility = LOG_KERN;
248 else if (!strcasecmp(facility, "USER"))
249 chan->facility = LOG_USER;
250 else if (!strcasecmp(facility, "MAIL"))
251 chan->facility = LOG_MAIL;
252 else if (!strcasecmp(facility, "DAEMON"))
253 chan->facility = LOG_DAEMON;
254 else if (!strcasecmp(facility, "AUTH"))
255 chan->facility = LOG_AUTH;
256 else if (!strcasecmp(facility, "SYSLOG"))
257 chan->facility = LOG_SYSLOG;
258 else if (!strcasecmp(facility, "LPR"))
259 chan->facility = LOG_LPR;
260 else if (!strcasecmp(facility, "NEWS"))
261 chan->facility = LOG_NEWS;
262 else if (!strcasecmp(facility, "UUCP"))
263 chan->facility = LOG_UUCP;
264 else if (!strcasecmp(facility, "CRON"))
265 chan->facility = LOG_CRON;
266 else if (!strcasecmp(facility, "LOCAL0"))
267 chan->facility = LOG_LOCAL0;
268 else if (!strcasecmp(facility, "LOCAL1"))
269 chan->facility = LOG_LOCAL1;
270 else if (!strcasecmp(facility, "LOCAL2"))
271 chan->facility = LOG_LOCAL2;
272 else if (!strcasecmp(facility, "LOCAL3"))
273 chan->facility = LOG_LOCAL3;
274 else if (!strcasecmp(facility, "LOCAL4"))
275 chan->facility = LOG_LOCAL4;
276 else if (!strcasecmp(facility, "LOCAL5"))
277 chan->facility = LOG_LOCAL5;
278 else if (!strcasecmp(facility, "LOCAL6"))
279 chan->facility = LOG_LOCAL6;
280 else if (!strcasecmp(facility, "LOCAL7"))
281 chan->facility = LOG_LOCAL7;
284 if (0 > chan->facility) {
285 fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
290 chan->type = LOGTYPE_SYSLOG;
291 snprintf(chan->filename, sizeof(chan->filename), "%s", channel);
292 openlog("asterisk", LOG_PID, chan->facility);
294 if (channel[0] == '/') {
295 if (!ast_strlen_zero(hostname)) {
296 snprintf(chan->filename, sizeof(chan->filename) - 1,"%s.%s", channel, hostname);
298 ast_copy_string(chan->filename, channel, sizeof(chan->filename));
302 if (!ast_strlen_zero(hostname)) {
303 snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s", ast_config_AST_LOG_DIR, channel, hostname);
305 snprintf(chan->filename, sizeof(chan->filename), "%s/%s", ast_config_AST_LOG_DIR, channel);
307 chan->fileptr = fopen(chan->filename, "a");
308 if (!chan->fileptr) {
309 /* Can't log here, since we're called with a lock */
310 fprintf(stderr, "Logger Warning: Unable to open log file '%s': %s\n", chan->filename, strerror(errno));
312 chan->type = LOGTYPE_FILE;
314 chan->logmask = make_components(components, lineno);
318 static void init_logger_chain(int reload, int locked)
320 struct logchannel *chan;
321 struct ast_config *cfg;
322 struct ast_variable *var;
324 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
326 if ((cfg = ast_config_load("logger.conf", config_flags)) == CONFIG_STATUS_FILEUNCHANGED)
329 /* delete our list of log channels */
331 AST_RWLIST_WRLOCK(&logchannels);
332 while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list)))
335 AST_RWLIST_UNLOCK(&logchannels);
342 /* If no config file, we're fine, set default options. */
345 fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
347 fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
348 if (!(chan = ast_calloc(1, sizeof(*chan))))
350 chan->type = LOGTYPE_CONSOLE;
351 chan->logmask = 28; /*warning,notice,error */
353 AST_RWLIST_WRLOCK(&logchannels);
354 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
356 AST_RWLIST_UNLOCK(&logchannels);
357 global_logmask |= chan->logmask;
361 if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
363 if (gethostname(hostname, sizeof(hostname) - 1)) {
364 ast_copy_string(hostname, "unknown", sizeof(hostname));
365 fprintf(stderr, "What box has no hostname???\n");
371 if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
372 ast_copy_string(dateformat, s, sizeof(dateformat));
374 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
375 if ((s = ast_variable_retrieve(cfg, "general", "queue_log")))
376 logfiles.queue_log = ast_true(s);
377 if ((s = ast_variable_retrieve(cfg, "general", "event_log")))
378 logfiles.event_log = 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));
381 if ((s = ast_variable_retrieve(cfg, "general", "exec_after_rotate")))
382 ast_copy_string(exec_after_rotate, s, sizeof(exec_after_rotate));
383 if ((s = ast_variable_retrieve(cfg, "general", "rotatestrategy"))) {
384 if (strcasecmp(s, "timestamp") == 0)
385 rotatestrategy = TIMESTAMP;
386 else if (strcasecmp(s, "rotate") == 0)
387 rotatestrategy = ROTATE;
388 else if (strcasecmp(s, "sequential") == 0)
389 rotatestrategy = SEQUENTIAL;
391 fprintf(stderr, "Unknown rotatestrategy: %s\n", s);
393 if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp"))) {
394 rotatestrategy = ast_true(s) ? TIMESTAMP : SEQUENTIAL;
395 fprintf(stderr, "rotatetimestamp option has been deprecated. Please use rotatestrategy instead.\n");
400 AST_RWLIST_WRLOCK(&logchannels);
401 var = ast_variable_browse(cfg, "logfiles");
402 for (; var; var = var->next) {
403 if (!(chan = make_logchannel(var->name, var->value, var->lineno)))
405 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
406 global_logmask |= chan->logmask;
409 AST_RWLIST_UNLOCK(&logchannels);
411 ast_config_destroy(cfg);
414 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
421 qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
422 vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
425 AST_RWLIST_RDLOCK(&logchannels);
427 fprintf(qlog, "%s\n", qlog_msg);
430 AST_RWLIST_UNLOCK(&logchannels);
433 static int rotate_file(const char *filename)
437 int x, y, which, found, res = 0, fd;
438 char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
440 switch (rotatestrategy) {
443 snprintf(new, sizeof(new), "%s.%d", filename, x);
444 fd = open(new, O_RDONLY);
450 if (rename(filename, new)) {
451 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
456 snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
457 if (rename(filename, new)) {
458 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
463 /* Find the next empty slot, including a possible suffix */
466 for (which = 0; which < sizeof(suffixes) / sizeof(suffixes[0]); which++) {
467 snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
468 fd = open(new, O_RDONLY);
480 /* Found an empty slot */
481 for (y = x; y > -1; y--) {
482 for (which = 0; which < sizeof(suffixes) / sizeof(suffixes[0]); which++) {
483 snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
484 fd = open(old, O_RDONLY);
486 /* Found the right suffix */
488 snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
489 if (rename(old, new)) {
490 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
498 /* Finally, rename the current file */
499 snprintf(new, sizeof(new), "%s.0", filename);
500 if (rename(filename, new)) {
501 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
506 if (!ast_strlen_zero(exec_after_rotate)) {
507 struct ast_channel *c = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Logger/rotate");
509 pbx_builtin_setvar_helper(c, "filename", filename);
510 pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
517 int reload_logger(int rotate)
519 char old[PATH_MAX] = "";
520 int event_rotate = rotate, queue_rotate = rotate;
521 struct logchannel *f;
525 AST_RWLIST_WRLOCK(&logchannels);
529 /* Check filesize - this one typically doesn't need an auto-rotate */
530 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
531 if (stat(old, &st) != 0 || st.st_size > 0x40000000) { /* Arbitrarily, 1 GB */
545 /* Check filesize - this one typically doesn't need an auto-rotate */
546 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
547 if (stat(old, &st) != 0 || st.st_size > 0x40000000) { /* Arbitrarily, 1 GB */
560 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
562 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
564 f->disabled = 0; /* Re-enable logging at reload */
565 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
567 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
568 fclose(f->fileptr); /* Close file */
571 rotate_file(f->filename);
575 filesize_reload_needed = 0;
577 init_logger_chain(rotate ? 0 : 1 /* reload */, 1 /* locked */);
579 if (logfiles.event_log) {
580 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
584 eventlog = fopen(old, "a");
586 ast_log(LOG_EVENT, "Restarted Asterisk Event Logger\n");
588 ast_verbose("Asterisk Event Logger restarted\n");
590 ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
595 if (logfiles.queue_log) {
596 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
600 qlog = fopen(old, "a");
602 AST_RWLIST_UNLOCK(&logchannels);
603 ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
604 AST_RWLIST_WRLOCK(&logchannels);
605 ast_log(LOG_EVENT, "Restarted Asterisk Queue Logger\n");
607 ast_verbose("Asterisk Queue Logger restarted\n");
609 ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
614 AST_RWLIST_UNLOCK(&logchannels);
619 static int handle_logger_reload(int fd, int argc, char *argv[])
621 if (reload_logger(0)) {
622 ast_cli(fd, "Failed to reload the logger\n");
623 return RESULT_FAILURE;
625 return RESULT_SUCCESS;
628 static int handle_logger_rotate(int fd, int argc, char *argv[])
630 if (reload_logger(1)) {
631 ast_cli(fd, "Failed to reload the logger and rotate log files\n");
632 return RESULT_FAILURE;
634 return RESULT_SUCCESS;
637 /*! \brief CLI command to show logging system configuration */
638 static int handle_logger_show_channels(int fd, int argc, char *argv[])
640 #define FORMATL "%-35.35s %-8.8s %-9.9s "
641 struct logchannel *chan;
643 ast_cli(fd,FORMATL, "Channel", "Type", "Status");
644 ast_cli(fd, "Configuration\n");
645 ast_cli(fd,FORMATL, "-------", "----", "------");
646 ast_cli(fd, "-------------\n");
647 AST_RWLIST_RDLOCK(&logchannels);
648 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
649 ast_cli(fd, FORMATL, chan->filename, chan->type==LOGTYPE_CONSOLE ? "Console" : (chan->type==LOGTYPE_SYSLOG ? "Syslog" : "File"),
650 chan->disabled ? "Disabled" : "Enabled");
652 if (chan->logmask & (1 << __LOG_DEBUG))
653 ast_cli(fd, "Debug ");
654 if (chan->logmask & (1 << __LOG_DTMF))
655 ast_cli(fd, "DTMF ");
656 if (chan->logmask & (1 << __LOG_VERBOSE))
657 ast_cli(fd, "Verbose ");
658 if (chan->logmask & (1 << __LOG_WARNING))
659 ast_cli(fd, "Warning ");
660 if (chan->logmask & (1 << __LOG_NOTICE))
661 ast_cli(fd, "Notice ");
662 if (chan->logmask & (1 << __LOG_ERROR))
663 ast_cli(fd, "Error ");
664 if (chan->logmask & (1 << __LOG_EVENT))
665 ast_cli(fd, "Event ");
668 AST_RWLIST_UNLOCK(&logchannels);
671 return RESULT_SUCCESS;
675 void (*verboser)(const char *string);
676 AST_LIST_ENTRY(verb) list;
679 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
681 static char logger_reload_help[] =
682 "Usage: logger reload\n"
683 " Reloads the logger subsystem state. Use after restarting syslogd(8) if you are using syslog logging.\n";
685 static char logger_rotate_help[] =
686 "Usage: logger rotate\n"
687 " Rotates and Reopens the log files.\n";
689 static char logger_show_channels_help[] =
690 "Usage: logger show channels\n"
691 " List configured logger channels.\n";
693 static struct ast_cli_entry cli_logger[] = {
694 { { "logger", "show", "channels", NULL },
695 handle_logger_show_channels, "List configured log channels",
696 logger_show_channels_help },
698 { { "logger", "reload", NULL },
699 handle_logger_reload, "Reopens the log files",
700 logger_reload_help },
702 { { "logger", "rotate", NULL },
703 handle_logger_rotate, "Rotates and reopens the log files",
704 logger_rotate_help },
707 static int handle_SIGXFSZ(int sig)
709 /* Indicate need to reload */
710 filesize_reload_needed = 1;
714 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, char *str)
718 if (level >= SYSLOG_NLEVELS) {
719 /* we are locked here, so cannot ast_log() */
720 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
724 if (level == __LOG_VERBOSE) {
725 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: %s", (long)GETTID(), str);
727 } else if (level == __LOG_DTMF) {
728 snprintf(buf, sizeof(buf), "DTMF[%ld]: %s", (long)GETTID(), str);
731 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: %s",
732 levels[level], (long)GETTID(), file, line, function, str);
735 term_strip(buf, buf, strlen(buf) + 1);
736 syslog(syslog_level_map[level], "%s", buf);
739 /* Print a normal log message to the channels */
740 static void logger_print_normal(struct logmsg *logmsg)
742 struct logchannel *chan = NULL;
745 AST_RWLIST_RDLOCK(&logchannels);
747 if (logfiles.event_log && logmsg->level == __LOG_EVENT) {
748 fprintf(eventlog, "%s asterisk[%ld]: %s", logmsg->date, (long)getpid(), logmsg->str);
750 AST_RWLIST_UNLOCK(&logchannels);
754 if (!AST_RWLIST_EMPTY(&logchannels)) {
755 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
756 /* If the channel is disabled, then move on to the next one */
759 /* Check syslog channels */
760 if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
761 ast_log_vsyslog(logmsg->level, logmsg->file, logmsg->line, logmsg->function, logmsg->str);
762 /* Console channels */
763 } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
765 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
767 /* If the level is verbose, then skip it */
768 if (logmsg->level == __LOG_VERBOSE)
771 /* Turn the numerical line number into a string */
772 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
773 /* Build string to print out */
774 snprintf(buf, sizeof(buf), "[%s] %s[%ld]: %s:%s %s: %s",
776 term_color(tmp1, levels[logmsg->level], colors[logmsg->level], 0, sizeof(tmp1)),
778 term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
779 term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
780 term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
783 ast_console_puts_mutable(buf);
785 } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
788 /* If no file pointer exists, skip it */
792 /* Print out to the file */
793 res = fprintf(chan->fileptr, "[%s] %s[%ld] %s: %s",
794 logmsg->date, levels[logmsg->level], (long)GETTID(), logmsg->file, logmsg->str);
795 if (res <= 0 && !ast_strlen_zero(logmsg->str)) {
796 fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
797 if (errno == ENOMEM || errno == ENOSPC)
798 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
800 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
801 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
803 } else if (res > 0) {
804 fflush(chan->fileptr);
808 } else if (logmsg->level != __LOG_VERBOSE) {
809 fputs(logmsg->str, stdout);
812 AST_RWLIST_UNLOCK(&logchannels);
814 /* If we need to reload because of the file size, then do so */
815 if (filesize_reload_needed) {
817 ast_log(LOG_EVENT, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
819 ast_verbose("Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
825 /* Print a verbose message to the verbosers */
826 static void logger_print_verbose(struct logmsg *logmsg)
828 struct verb *v = NULL;
830 /* Iterate through the list of verbosers and pass them the log message string */
831 AST_RWLIST_RDLOCK(&verbosers);
832 AST_RWLIST_TRAVERSE(&verbosers, v, list)
833 v->verboser(logmsg->str);
834 AST_RWLIST_UNLOCK(&verbosers);
839 /* Actual logging thread */
840 static void *logger_thread(void *data)
842 struct logmsg *next = NULL, *msg = NULL;
845 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
846 AST_LIST_LOCK(&logmsgs);
847 if (AST_LIST_EMPTY(&logmsgs))
848 ast_cond_wait(&logcond, &logmsgs.lock);
849 next = AST_LIST_FIRST(&logmsgs);
850 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
851 AST_LIST_UNLOCK(&logmsgs);
853 /* If we should stop, then stop */
854 if (close_logger_thread)
857 /* Otherwise go through and process each message in the order added */
858 while ((msg = next)) {
859 /* Get the next entry now so that we can free our current structure later */
860 next = AST_LIST_NEXT(msg, list);
862 /* Depending on the type, send it to the proper function */
863 if (msg->type == LOGMSG_NORMAL)
864 logger_print_normal(msg);
865 else if (msg->type == LOGMSG_VERBOSE)
866 logger_print_verbose(msg);
868 /* Free the data since we are done */
876 int init_logger(void)
881 /* auto rotate if sig SIGXFSZ comes a-knockin */
882 (void) signal(SIGXFSZ,(void *) handle_SIGXFSZ);
884 /* start logger thread */
885 ast_cond_init(&logcond, NULL);
886 if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
887 ast_cond_destroy(&logcond);
891 /* register the logger cli commands */
892 ast_cli_register_multiple(cli_logger, sizeof(cli_logger) / sizeof(struct ast_cli_entry));
894 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
896 /* create log channels */
897 init_logger_chain(0 /* reload */, 0 /* locked */);
899 /* create the eventlog */
900 if (logfiles.event_log) {
901 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
902 eventlog = fopen(tmp, "a");
904 ast_log(LOG_EVENT, "Started Asterisk Event Logger\n");
906 ast_verbose("Asterisk Event Logger Started %s\n", tmp);
908 ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
913 if (logfiles.queue_log) {
914 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
915 qlog = fopen(tmp, "a");
916 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
921 void close_logger(void)
923 struct logchannel *f = NULL;
925 /* Stop logger thread */
926 AST_LIST_LOCK(&logmsgs);
927 close_logger_thread = 1;
928 ast_cond_signal(&logcond);
929 AST_LIST_UNLOCK(&logmsgs);
931 AST_RWLIST_WRLOCK(&logchannels);
943 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
944 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
950 closelog(); /* syslog */
952 AST_RWLIST_UNLOCK(&logchannels);
958 * \brief send log messages to syslog and/or the console
960 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
962 struct logmsg *logmsg = NULL;
963 struct ast_str *buf = NULL;
965 struct timeval tv = ast_tvnow();
969 if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
972 if (AST_RWLIST_EMPTY(&logchannels)) {
974 * we don't have the logger chain configured yet,
975 * so just log to stdout
977 if (level != __LOG_VERBOSE) {
980 res = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
982 if (res != AST_DYNSTR_BUILD_FAILED) {
983 term_filter_escapes(buf->str);
984 fputs(buf->str, stdout);
990 /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
991 are non-zero; LOG_DEBUG messages can still be displayed if option_debug
992 is zero, if option_verbose is non-zero (this allows for 'level zero'
993 LOG_DEBUG messages to be displayed, if the logmask on any channel
996 if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
999 /* Ignore anything that never gets logged anywhere */
1000 if (!(global_logmask & (1 << level)))
1005 res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1008 /* If the build failed, then abort and free this structure */
1009 if (res == AST_DYNSTR_BUILD_FAILED)
1012 /* Create a new logging message */
1013 if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1016 /* Copy string over */
1017 strcpy(logmsg->str, buf->str);
1019 /* Set type to be normal */
1020 logmsg->type = LOGMSG_NORMAL;
1022 /* Create our date/time */
1023 ast_localtime(&tv, &tm, NULL);
1024 ast_strftime(logmsg->date, sizeof(logmsg->date), dateformat, &tm);
1026 /* Copy over data */
1027 logmsg->level = level;
1028 logmsg->file = file;
1029 logmsg->line = line;
1030 logmsg->function = function;
1032 /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1033 if (logthread != AST_PTHREADT_NULL) {
1034 AST_LIST_LOCK(&logmsgs);
1035 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1036 ast_cond_signal(&logcond);
1037 AST_LIST_UNLOCK(&logmsgs);
1039 logger_print_normal(logmsg);
1046 void ast_backtrace(void)
1054 if ((addresses = ast_calloc(MAX_BACKTRACE_FRAMES, sizeof(*addresses)))) {
1055 count = backtrace(addresses, MAX_BACKTRACE_FRAMES);
1056 if ((strings = backtrace_symbols(addresses, count))) {
1057 ast_debug(1, "Got %d backtrace record%c\n", count, count != 1 ? 's' : ' ');
1058 for (i=0; i < count ; i++) {
1059 #if __WORDSIZE == 32
1060 ast_log(LOG_DEBUG, "#%d: [%08X] %s\n", i, (unsigned int)addresses[i], strings[i]);
1061 #elif __WORDSIZE == 64
1062 ast_log(LOG_DEBUG, "#%d: [%016lX] %s\n", i, (unsigned long)addresses[i], strings[i]);
1067 ast_debug(1, "Could not allocate memory for backtrace\n");
1072 ast_log(LOG_WARNING, "Must run configure with '--enable-dev-mode' for stack backtraces.\n");
1074 #else /* ndef linux */
1075 ast_log(LOG_WARNING, "Inline stack backtraces are only available on the Linux platform.\n");
1079 void ast_verbose(const char *fmt, ...)
1081 struct logmsg *logmsg = NULL;
1082 struct ast_str *buf = NULL;
1086 if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
1089 if (ast_opt_timestamp) {
1096 ast_localtime(&tv, &tm, NULL);
1097 ast_strftime(date, sizeof(date), dateformat, &tm);
1098 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1099 sprintf(datefmt, "[%s] %s", date, fmt);
1105 res = ast_str_set_va(&buf, 0, fmt, ap);
1108 /* If the build failed then we can drop this allocated message */
1109 if (res == AST_DYNSTR_BUILD_FAILED)
1112 if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1115 strcpy(logmsg->str, buf->str);
1117 ast_log(LOG_VERBOSE, logmsg->str);
1120 logmsg->type = LOGMSG_VERBOSE;
1122 /* Add to the list and poke the thread if possible */
1123 if (logthread != AST_PTHREADT_NULL) {
1124 AST_LIST_LOCK(&logmsgs);
1125 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1126 ast_cond_signal(&logcond);
1127 AST_LIST_UNLOCK(&logmsgs);
1129 logger_print_verbose(logmsg);
1134 int ast_register_verbose(void (*v)(const char *string))
1138 if (!(verb = ast_malloc(sizeof(*verb))))
1143 AST_RWLIST_WRLOCK(&verbosers);
1144 AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1145 AST_RWLIST_UNLOCK(&verbosers);
1150 int ast_unregister_verbose(void (*v)(const char *string))
1154 AST_RWLIST_WRLOCK(&verbosers);
1155 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1156 if (cur->verboser == v) {
1157 AST_RWLIST_REMOVE_CURRENT(&verbosers, list);
1162 AST_RWLIST_TRAVERSE_SAFE_END
1163 AST_RWLIST_UNLOCK(&verbosers);
1165 return cur ? 0 : -1;