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;
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 /*! \brief Logging channels used in the Asterisk logging system */
152 static char *levels[] = {
162 /*! \brief Colors used in the console for logging */
163 static int colors[] = {
173 AST_THREADSTORAGE(verbose_buf);
174 #define VERBOSE_BUF_INIT_SIZE 256
176 AST_THREADSTORAGE(log_buf);
177 #define LOG_BUF_INIT_SIZE 256
179 static int make_components(const char *s, int lineno)
183 char *stringp = ast_strdupa(s);
185 while ((w = strsep(&stringp, ","))) {
186 w = ast_skip_blanks(w);
187 if (!strcasecmp(w, "error"))
188 res |= (1 << __LOG_ERROR);
189 else if (!strcasecmp(w, "warning"))
190 res |= (1 << __LOG_WARNING);
191 else if (!strcasecmp(w, "notice"))
192 res |= (1 << __LOG_NOTICE);
193 else if (!strcasecmp(w, "event"))
194 res |= (1 << __LOG_EVENT);
195 else if (!strcasecmp(w, "debug"))
196 res |= (1 << __LOG_DEBUG);
197 else if (!strcasecmp(w, "verbose"))
198 res |= (1 << __LOG_VERBOSE);
199 else if (!strcasecmp(w, "dtmf"))
200 res |= (1 << __LOG_DTMF);
202 fprintf(stderr, "Logfile Warning: Unknown keyword '%s' at line %d of logger.conf\n", w, lineno);
209 static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno)
211 struct logchannel *chan;
217 if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan))))
220 if (!strcasecmp(channel, "console")) {
221 chan->type = LOGTYPE_CONSOLE;
222 } else if (!strncasecmp(channel, "syslog", 6)) {
225 * syslog.facility => level,level,level
227 facility = strchr(channel, '.');
228 if (!facility++ || !facility) {
234 * Walk through the list of facilitynames (defined in sys/syslog.h)
235 * to see if we can find the one we have been given
238 cptr = facilitynames;
239 while (cptr->c_name) {
240 if (!strcasecmp(facility, cptr->c_name)) {
241 chan->facility = cptr->c_val;
248 if (!strcasecmp(facility, "kern"))
249 chan->facility = LOG_KERN;
250 else if (!strcasecmp(facility, "USER"))
251 chan->facility = LOG_USER;
252 else if (!strcasecmp(facility, "MAIL"))
253 chan->facility = LOG_MAIL;
254 else if (!strcasecmp(facility, "DAEMON"))
255 chan->facility = LOG_DAEMON;
256 else if (!strcasecmp(facility, "AUTH"))
257 chan->facility = LOG_AUTH;
258 else if (!strcasecmp(facility, "SYSLOG"))
259 chan->facility = LOG_SYSLOG;
260 else if (!strcasecmp(facility, "LPR"))
261 chan->facility = LOG_LPR;
262 else if (!strcasecmp(facility, "NEWS"))
263 chan->facility = LOG_NEWS;
264 else if (!strcasecmp(facility, "UUCP"))
265 chan->facility = LOG_UUCP;
266 else if (!strcasecmp(facility, "CRON"))
267 chan->facility = LOG_CRON;
268 else if (!strcasecmp(facility, "LOCAL0"))
269 chan->facility = LOG_LOCAL0;
270 else if (!strcasecmp(facility, "LOCAL1"))
271 chan->facility = LOG_LOCAL1;
272 else if (!strcasecmp(facility, "LOCAL2"))
273 chan->facility = LOG_LOCAL2;
274 else if (!strcasecmp(facility, "LOCAL3"))
275 chan->facility = LOG_LOCAL3;
276 else if (!strcasecmp(facility, "LOCAL4"))
277 chan->facility = LOG_LOCAL4;
278 else if (!strcasecmp(facility, "LOCAL5"))
279 chan->facility = LOG_LOCAL5;
280 else if (!strcasecmp(facility, "LOCAL6"))
281 chan->facility = LOG_LOCAL6;
282 else if (!strcasecmp(facility, "LOCAL7"))
283 chan->facility = LOG_LOCAL7;
286 if (0 > chan->facility) {
287 fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
292 chan->type = LOGTYPE_SYSLOG;
293 snprintf(chan->filename, sizeof(chan->filename), "%s", channel);
294 openlog("asterisk", LOG_PID, chan->facility);
296 if (channel[0] == '/') {
297 if (!ast_strlen_zero(hostname)) {
298 snprintf(chan->filename, sizeof(chan->filename) - 1,"%s.%s", channel, hostname);
300 ast_copy_string(chan->filename, channel, sizeof(chan->filename));
304 if (!ast_strlen_zero(hostname)) {
305 snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s", ast_config_AST_LOG_DIR, channel, hostname);
307 snprintf(chan->filename, sizeof(chan->filename), "%s/%s", ast_config_AST_LOG_DIR, channel);
309 chan->fileptr = fopen(chan->filename, "a");
310 if (!chan->fileptr) {
311 /* Can't log here, since we're called with a lock */
312 fprintf(stderr, "Logger Warning: Unable to open log file '%s': %s\n", chan->filename, strerror(errno));
314 chan->type = LOGTYPE_FILE;
316 chan->logmask = make_components(components, lineno);
320 static void init_logger_chain(int reload, int locked)
322 struct logchannel *chan;
323 struct ast_config *cfg;
324 struct ast_variable *var;
326 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
328 if ((cfg = ast_config_load("logger.conf", config_flags)) == CONFIG_STATUS_FILEUNCHANGED)
331 /* delete our list of log channels */
333 AST_RWLIST_WRLOCK(&logchannels);
334 while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list)))
337 AST_RWLIST_UNLOCK(&logchannels);
344 /* If no config file, we're fine, set default options. */
347 fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
349 fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
350 if (!(chan = ast_calloc(1, sizeof(*chan))))
352 chan->type = LOGTYPE_CONSOLE;
353 chan->logmask = 28; /*warning,notice,error */
355 AST_RWLIST_WRLOCK(&logchannels);
356 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
358 AST_RWLIST_UNLOCK(&logchannels);
359 global_logmask |= chan->logmask;
363 if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
365 if (gethostname(hostname, sizeof(hostname) - 1)) {
366 ast_copy_string(hostname, "unknown", sizeof(hostname));
367 fprintf(stderr, "What box has no hostname???\n");
373 if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
374 ast_copy_string(dateformat, s, sizeof(dateformat));
376 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
377 if ((s = ast_variable_retrieve(cfg, "general", "queue_log")))
378 logfiles.queue_log = ast_true(s);
379 if ((s = ast_variable_retrieve(cfg, "general", "event_log")))
380 logfiles.event_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_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
423 if (ast_check_realtime("queue_log")) {
425 vsnprintf(qlog_msg, sizeof(qlog_msg), fmt, ap);
427 snprintf(time_str, sizeof(time_str), "%ld", (long)time(NULL));
428 ast_store_realtime("queue_log", "time", time_str,
430 "queuename", queuename,
438 qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
439 vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
442 AST_RWLIST_RDLOCK(&logchannels);
444 fprintf(qlog, "%s\n", qlog_msg);
447 AST_RWLIST_UNLOCK(&logchannels);
451 static int rotate_file(const char *filename)
455 int x, y, which, found, res = 0, fd;
456 char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
458 switch (rotatestrategy) {
461 snprintf(new, sizeof(new), "%s.%d", filename, x);
462 fd = open(new, O_RDONLY);
468 if (rename(filename, new)) {
469 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
474 snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
475 if (rename(filename, new)) {
476 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
481 /* Find the next empty slot, including a possible suffix */
484 for (which = 0; which < sizeof(suffixes) / sizeof(suffixes[0]); which++) {
485 snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
486 fd = open(new, O_RDONLY);
498 /* Found an empty slot */
499 for (y = x; y > -1; y--) {
500 for (which = 0; which < sizeof(suffixes) / sizeof(suffixes[0]); which++) {
501 snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
502 fd = open(old, O_RDONLY);
504 /* Found the right suffix */
506 snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
507 if (rename(old, new)) {
508 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
516 /* Finally, rename the current file */
517 snprintf(new, sizeof(new), "%s.0", filename);
518 if (rename(filename, new)) {
519 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
524 if (!ast_strlen_zero(exec_after_rotate)) {
525 struct ast_channel *c = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Logger/rotate");
527 pbx_builtin_setvar_helper(c, "filename", filename);
528 pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
535 static int reload_logger(int rotate)
537 char old[PATH_MAX] = "";
538 int event_rotate = rotate, queue_rotate = rotate;
539 struct logchannel *f;
543 AST_RWLIST_WRLOCK(&logchannels);
547 /* Check filesize - this one typically doesn't need an auto-rotate */
548 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
549 if (stat(old, &st) != 0 || st.st_size > 0x40000000) { /* Arbitrarily, 1 GB */
563 /* Check filesize - this one typically doesn't need an auto-rotate */
564 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
565 if (stat(old, &st) != 0 || st.st_size > 0x40000000) { /* Arbitrarily, 1 GB */
578 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
580 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
582 f->disabled = 0; /* Re-enable logging at reload */
583 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
585 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
586 fclose(f->fileptr); /* Close file */
589 rotate_file(f->filename);
593 filesize_reload_needed = 0;
595 init_logger_chain(rotate ? 0 : 1 /* reload */, 1 /* locked */);
597 if (logfiles.event_log) {
598 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
602 eventlog = fopen(old, "a");
604 ast_log(LOG_EVENT, "Restarted Asterisk Event Logger\n");
605 ast_verb(1, "Asterisk Event Logger restarted\n");
607 ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
612 if (logfiles.queue_log) {
613 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
617 qlog = fopen(old, "a");
619 AST_RWLIST_UNLOCK(&logchannels);
620 ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
621 AST_RWLIST_WRLOCK(&logchannels);
622 ast_log(LOG_EVENT, "Restarted Asterisk Queue Logger\n");
623 ast_verb(1, "Asterisk Queue Logger restarted\n");
625 ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
630 AST_RWLIST_UNLOCK(&logchannels);
635 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
636 a full Asterisk reload) */
637 int logger_reload(void)
640 return RESULT_FAILURE;
641 return RESULT_SUCCESS;
644 static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
648 e->command = "logger reload";
650 "Usage: logger reload\n"
651 " Reloads the logger subsystem state. Use after restarting syslogd(8) if you are using syslog logging.\n";
656 if (reload_logger(0)) {
657 ast_cli(a->fd, "Failed to reload the logger\n");
663 static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
667 e->command = "logger rotate";
669 "Usage: logger rotate\n"
670 " Rotates and Reopens the log files.\n";
675 if (reload_logger(1)) {
676 ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
682 /*! \brief CLI command to show logging system configuration */
683 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
685 #define FORMATL "%-35.35s %-8.8s %-9.9s "
686 struct logchannel *chan;
689 e->command = "logger show channels";
691 "Usage: logger show channels\n"
692 " List configured logger channels.\n";
697 ast_cli(a->fd,FORMATL, "Channel", "Type", "Status");
698 ast_cli(a->fd, "Configuration\n");
699 ast_cli(a->fd,FORMATL, "-------", "----", "------");
700 ast_cli(a->fd, "-------------\n");
701 AST_RWLIST_RDLOCK(&logchannels);
702 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
703 ast_cli(a->fd, FORMATL, chan->filename, chan->type==LOGTYPE_CONSOLE ? "Console" : (chan->type==LOGTYPE_SYSLOG ? "Syslog" : "File"),
704 chan->disabled ? "Disabled" : "Enabled");
705 ast_cli(a->fd, " - ");
706 if (chan->logmask & (1 << __LOG_DEBUG))
707 ast_cli(a->fd, "Debug ");
708 if (chan->logmask & (1 << __LOG_DTMF))
709 ast_cli(a->fd, "DTMF ");
710 if (chan->logmask & (1 << __LOG_VERBOSE))
711 ast_cli(a->fd, "Verbose ");
712 if (chan->logmask & (1 << __LOG_WARNING))
713 ast_cli(a->fd, "Warning ");
714 if (chan->logmask & (1 << __LOG_NOTICE))
715 ast_cli(a->fd, "Notice ");
716 if (chan->logmask & (1 << __LOG_ERROR))
717 ast_cli(a->fd, "Error ");
718 if (chan->logmask & (1 << __LOG_EVENT))
719 ast_cli(a->fd, "Event ");
720 ast_cli(a->fd, "\n");
722 AST_RWLIST_UNLOCK(&logchannels);
723 ast_cli(a->fd, "\n");
729 void (*verboser)(const char *string);
730 AST_LIST_ENTRY(verb) list;
733 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
735 static struct ast_cli_entry cli_logger[] = {
736 AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
737 AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
738 AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files")
741 static int handle_SIGXFSZ(int sig)
743 /* Indicate need to reload */
744 filesize_reload_needed = 1;
748 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, char *str)
752 if (level >= SYSLOG_NLEVELS) {
753 /* we are locked here, so cannot ast_log() */
754 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
758 if (level == __LOG_VERBOSE) {
759 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: %s", (long)GETTID(), str);
761 } else if (level == __LOG_DTMF) {
762 snprintf(buf, sizeof(buf), "DTMF[%ld]: %s", (long)GETTID(), str);
765 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: %s",
766 levels[level], (long)GETTID(), file, line, function, str);
769 term_strip(buf, buf, strlen(buf) + 1);
770 syslog(syslog_level_map[level], "%s", buf);
773 /*! \brief Print a normal log message to the channels */
774 static void logger_print_normal(struct logmsg *logmsg)
776 struct logchannel *chan = NULL;
779 AST_RWLIST_RDLOCK(&logchannels);
781 if (logfiles.event_log && logmsg->level == __LOG_EVENT) {
782 fprintf(eventlog, "%s asterisk[%ld]: %s", logmsg->date, (long)getpid(), logmsg->str);
784 AST_RWLIST_UNLOCK(&logchannels);
788 if (!AST_RWLIST_EMPTY(&logchannels)) {
789 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
790 /* If the channel is disabled, then move on to the next one */
793 /* Check syslog channels */
794 if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
795 ast_log_vsyslog(logmsg->level, logmsg->file, logmsg->line, logmsg->function, logmsg->str);
796 /* Console channels */
797 } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
799 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
801 /* If the level is verbose, then skip it */
802 if (logmsg->level == __LOG_VERBOSE)
805 /* Turn the numerical line number into a string */
806 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
807 /* Build string to print out */
808 snprintf(buf, sizeof(buf), "[%s] %s[%ld]: %s:%s %s: %s",
810 term_color(tmp1, levels[logmsg->level], colors[logmsg->level], 0, sizeof(tmp1)),
812 term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
813 term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
814 term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
817 ast_console_puts_mutable(buf);
819 } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
822 /* If no file pointer exists, skip it */
826 /* Print out to the file */
827 res = fprintf(chan->fileptr, "[%s] %s[%ld] %s: %s",
828 logmsg->date, levels[logmsg->level], (long)GETTID(), logmsg->file, logmsg->str);
829 if (res <= 0 && !ast_strlen_zero(logmsg->str)) {
830 fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
831 if (errno == ENOMEM || errno == ENOSPC)
832 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
834 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
835 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
837 } else if (res > 0) {
838 fflush(chan->fileptr);
842 } else if (logmsg->level != __LOG_VERBOSE) {
843 fputs(logmsg->str, stdout);
846 AST_RWLIST_UNLOCK(&logchannels);
848 /* If we need to reload because of the file size, then do so */
849 if (filesize_reload_needed) {
851 ast_log(LOG_EVENT, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
852 ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
858 /*! \brief Print a verbose message to the verbosers */
859 static void logger_print_verbose(struct logmsg *logmsg)
861 struct verb *v = NULL;
863 /* Iterate through the list of verbosers and pass them the log message string */
864 AST_RWLIST_RDLOCK(&verbosers);
865 AST_RWLIST_TRAVERSE(&verbosers, v, list)
866 v->verboser(logmsg->str);
867 AST_RWLIST_UNLOCK(&verbosers);
872 /*! \brief Actual logging thread */
873 static void *logger_thread(void *data)
875 struct logmsg *next = NULL, *msg = NULL;
878 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
879 AST_LIST_LOCK(&logmsgs);
880 if (AST_LIST_EMPTY(&logmsgs))
881 ast_cond_wait(&logcond, &logmsgs.lock);
882 next = AST_LIST_FIRST(&logmsgs);
883 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
884 AST_LIST_UNLOCK(&logmsgs);
886 /* Otherwise go through and process each message in the order added */
887 while ((msg = next)) {
888 /* Get the next entry now so that we can free our current structure later */
889 next = AST_LIST_NEXT(msg, list);
891 /* Depending on the type, send it to the proper function */
892 if (msg->type == LOGMSG_NORMAL)
893 logger_print_normal(msg);
894 else if (msg->type == LOGMSG_VERBOSE)
895 logger_print_verbose(msg);
897 /* Free the data since we are done */
901 /* If we should stop, then stop */
902 if (close_logger_thread)
909 int init_logger(void)
914 /* auto rotate if sig SIGXFSZ comes a-knockin */
915 (void) signal(SIGXFSZ,(void *) handle_SIGXFSZ);
917 /* start logger thread */
918 ast_cond_init(&logcond, NULL);
919 if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
920 ast_cond_destroy(&logcond);
924 /* register the logger cli commands */
925 ast_cli_register_multiple(cli_logger, sizeof(cli_logger) / sizeof(struct ast_cli_entry));
927 ast_mkdir(ast_config_AST_LOG_DIR, 0777);
929 /* create log channels */
930 init_logger_chain(0 /* reload */, 0 /* locked */);
932 /* create the eventlog */
933 if (logfiles.event_log) {
934 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
935 eventlog = fopen(tmp, "a");
937 ast_log(LOG_EVENT, "Started Asterisk Event Logger\n");
938 ast_verb(1, "Asterisk Event Logger Started %s\n", tmp);
940 ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
945 if (logfiles.queue_log) {
946 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
947 qlog = fopen(tmp, "a");
948 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
953 void close_logger(void)
955 struct logchannel *f = NULL;
957 /* Stop logger thread */
958 AST_LIST_LOCK(&logmsgs);
959 close_logger_thread = 1;
960 ast_cond_signal(&logcond);
961 AST_LIST_UNLOCK(&logmsgs);
963 if (logthread != AST_PTHREADT_NULL)
964 pthread_join(logthread, NULL);
966 AST_RWLIST_WRLOCK(&logchannels);
978 AST_RWLIST_TRAVERSE(&logchannels, f, list) {
979 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
985 closelog(); /* syslog */
987 AST_RWLIST_UNLOCK(&logchannels);
993 * \brief send log messages to syslog and/or the console
995 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
997 struct logmsg *logmsg = NULL;
998 struct ast_str *buf = NULL;
1000 struct timeval tv = ast_tvnow();
1004 if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1007 if (AST_RWLIST_EMPTY(&logchannels)) {
1009 * we don't have the logger chain configured yet,
1010 * so just log to stdout
1012 if (level != __LOG_VERBOSE) {
1015 res = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1017 if (res != AST_DYNSTR_BUILD_FAILED) {
1018 term_filter_escapes(buf->str);
1019 fputs(buf->str, stdout);
1025 /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
1026 are non-zero; LOG_DEBUG messages can still be displayed if option_debug
1027 is zero, if option_verbose is non-zero (this allows for 'level zero'
1028 LOG_DEBUG messages to be displayed, if the logmask on any channel
1031 if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
1034 /* Ignore anything that never gets logged anywhere */
1035 if (!(global_logmask & (1 << level)))
1040 res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1043 /* If the build failed, then abort and free this structure */
1044 if (res == AST_DYNSTR_BUILD_FAILED)
1047 /* Create a new logging message */
1048 if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1051 /* Copy string over */
1052 strcpy(logmsg->str, buf->str);
1054 /* Set type to be normal */
1055 logmsg->type = LOGMSG_NORMAL;
1057 /* Create our date/time */
1058 ast_localtime(&tv, &tm, NULL);
1059 ast_strftime(logmsg->date, sizeof(logmsg->date), dateformat, &tm);
1061 /* Copy over data */
1062 logmsg->level = level;
1063 logmsg->file = file;
1064 logmsg->line = line;
1065 logmsg->function = function;
1067 /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1068 if (logthread != AST_PTHREADT_NULL) {
1069 AST_LIST_LOCK(&logmsgs);
1070 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1071 ast_cond_signal(&logcond);
1072 AST_LIST_UNLOCK(&logmsgs);
1074 logger_print_normal(logmsg);
1081 void ast_backtrace(void)
1084 int count = 0, i = 0;
1088 if ((addresses = ast_calloc(MAX_BACKTRACE_FRAMES, sizeof(*addresses)))) {
1089 count = backtrace(addresses, MAX_BACKTRACE_FRAMES);
1090 if ((strings = backtrace_symbols(addresses, count))) {
1091 ast_debug(1, "Got %d backtrace record%c\n", count, count != 1 ? 's' : ' ');
1092 for (i = 0; i < count; i++) {
1093 #if __WORDSIZE == 32
1094 ast_log(LOG_DEBUG, "#%d: [%08X] %s\n", i, (unsigned int)addresses[i], strings[i]);
1095 #elif __WORDSIZE == 64
1096 ast_log(LOG_DEBUG, "#%d: [%016lX] %s\n", i, (unsigned long)addresses[i], strings[i]);
1101 ast_debug(1, "Could not allocate memory for backtrace\n");
1103 ast_free(addresses);
1106 ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1110 void ast_verbose(const char *fmt, ...)
1112 struct logmsg *logmsg = NULL;
1113 struct ast_str *buf = NULL;
1117 if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
1120 if (ast_opt_timestamp) {
1127 ast_localtime(&tv, &tm, NULL);
1128 ast_strftime(date, sizeof(date), dateformat, &tm);
1129 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1130 sprintf(datefmt, "[%s] %s", date, fmt);
1136 res = ast_str_set_va(&buf, 0, fmt, ap);
1139 /* If the build failed then we can drop this allocated message */
1140 if (res == AST_DYNSTR_BUILD_FAILED)
1143 if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1146 strcpy(logmsg->str, buf->str);
1148 ast_log(LOG_VERBOSE, logmsg->str);
1151 logmsg->type = LOGMSG_VERBOSE;
1153 /* Add to the list and poke the thread if possible */
1154 if (logthread != AST_PTHREADT_NULL) {
1155 AST_LIST_LOCK(&logmsgs);
1156 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1157 ast_cond_signal(&logcond);
1158 AST_LIST_UNLOCK(&logmsgs);
1160 logger_print_verbose(logmsg);
1165 int ast_register_verbose(void (*v)(const char *string))
1169 if (!(verb = ast_malloc(sizeof(*verb))))
1174 AST_RWLIST_WRLOCK(&verbosers);
1175 AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1176 AST_RWLIST_UNLOCK(&verbosers);
1181 int ast_unregister_verbose(void (*v)(const char *string))
1185 AST_RWLIST_WRLOCK(&verbosers);
1186 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1187 if (cur->verboser == v) {
1188 AST_RWLIST_REMOVE_CURRENT(list);
1193 AST_RWLIST_TRAVERSE_SAFE_END;
1194 AST_RWLIST_UNLOCK(&verbosers);
1196 return cur ? 0 : -1;