4 * Mark Spencer <markster@marko.net>
6 * Copyright(C)1999, Linux Support Services, Inc.
8 * Distributed under the terms of the GNU General Public License (GPL) Version 2
19 #include <asterisk/lock.h>
20 #include <asterisk/options.h>
21 #include <asterisk/channel.h>
22 #include <asterisk/config.h>
23 #include <asterisk/term.h>
24 #include <asterisk/cli.h>
25 #include <asterisk/utils.h>
26 #include <asterisk/manager.h>
34 #define SYSLOG_NAMES /* so we can map syslog facilities names to their numeric values,
35 from <syslog.h> which is included by logger.h */
37 static int syslog_level_map[] = {
39 LOG_INFO, /* arbitrary equivalent of LOG_EVENT */
46 #define SYSLOG_NLEVELS 6
48 #include <asterisk/logger.h>
50 #define MAX_MSG_QUEUE 200
52 #if defined(__linux__) && defined(__NR_gettid)
53 #include <asm/unistd.h>
54 #define GETTID() syscall(__NR_gettid)
56 #define GETTID() getpid()
59 static char dateformat[256] = "%b %e %T"; /* Original Asterisk Format */
61 AST_MUTEX_DEFINE_STATIC(msglist_lock);
62 AST_MUTEX_DEFINE_STATIC(loglock);
63 static int pending_logger_reload = 0;
64 static int global_logmask = -1;
67 unsigned int queue_log:1;
68 unsigned int event_log:1;
69 } logfiles = { 1, 1 };
71 static struct msglist {
74 } *list = NULL, *last = NULL;
76 static char hostname[256];
85 int logmask; /* What to log to this channel */
86 int disabled; /* If this channel is disabled or not */
87 int facility; /* syslog facility */
88 enum logtypes type; /* Type of log channel */
89 FILE *fileptr; /* logfile logging file pointer */
90 char filename[256]; /* Filename */
91 struct logchannel *next; /* Next channel in chain */
94 static struct logchannel *logchannels = NULL;
96 static int msgcnt = 0;
98 static FILE *eventlog = NULL;
100 static char *levels[] = {
109 static int colors[] = {
118 static int make_components(char *s, int lineno)
124 w = strsep(&stringp, ",");
126 while(*w && (*w < 33))
128 if (!strcasecmp(w, "error"))
129 res |= (1 << __LOG_ERROR);
130 else if (!strcasecmp(w, "warning"))
131 res |= (1 << __LOG_WARNING);
132 else if (!strcasecmp(w, "notice"))
133 res |= (1 << __LOG_NOTICE);
134 else if (!strcasecmp(w, "event"))
135 res |= (1 << __LOG_EVENT);
136 else if (!strcasecmp(w, "debug"))
137 res |= (1 << __LOG_DEBUG);
138 else if (!strcasecmp(w, "verbose"))
139 res |= (1 << __LOG_VERBOSE);
141 fprintf(stderr, "Logfile Warning: Unknown keyword '%s' at line %d of logger.conf\n", w, lineno);
143 w = strsep(&stringp, ",");
148 static struct logchannel *make_logchannel(char *channel, char *components, int lineno)
150 struct logchannel *chan;
156 if (ast_strlen_zero(channel))
158 chan = malloc(sizeof(struct logchannel));
160 if (!chan) /* Can't allocate memory */
163 memset(chan, 0, sizeof(struct logchannel));
164 if (!strcasecmp(channel, "console")) {
165 chan->type = LOGTYPE_CONSOLE;
166 } else if (!strncasecmp(channel, "syslog", 6)) {
169 * syslog.facility => level,level,level
171 facility = strchr(channel, '.');
172 if(!facility++ || !facility) {
178 * Walk through the list of facilitynames (defined in sys/syslog.h)
179 * to see if we can find the one we have been given
182 cptr = facilitynames;
183 while (cptr->c_name) {
184 if (!strcasecmp(facility, cptr->c_name)) {
185 chan->facility = cptr->c_val;
192 if (!strcasecmp(facility, "kern"))
193 chan->facility = LOG_KERN;
194 else if (!strcasecmp(facility, "USER"))
195 chan->facility = LOG_USER;
196 else if (!strcasecmp(facility, "MAIL"))
197 chan->facility = LOG_MAIL;
198 else if (!strcasecmp(facility, "DAEMON"))
199 chan->facility = LOG_DAEMON;
200 else if (!strcasecmp(facility, "AUTH"))
201 chan->facility = LOG_AUTH;
202 else if (!strcasecmp(facility, "SYSLOG"))
203 chan->facility = LOG_SYSLOG;
204 else if (!strcasecmp(facility, "LPR"))
205 chan->facility = LOG_LPR;
206 else if (!strcasecmp(facility, "NEWS"))
207 chan->facility = LOG_NEWS;
208 else if (!strcasecmp(facility, "UUCP"))
209 chan->facility = LOG_UUCP;
210 else if (!strcasecmp(facility, "CRON"))
211 chan->facility = LOG_CRON;
212 else if (!strcasecmp(facility, "LOCAL0"))
213 chan->facility = LOG_LOCAL0;
214 else if (!strcasecmp(facility, "LOCAL1"))
215 chan->facility = LOG_LOCAL1;
216 else if (!strcasecmp(facility, "LOCAL2"))
217 chan->facility = LOG_LOCAL2;
218 else if (!strcasecmp(facility, "LOCAL3"))
219 chan->facility = LOG_LOCAL3;
220 else if (!strcasecmp(facility, "LOCAL4"))
221 chan->facility = LOG_LOCAL4;
222 else if (!strcasecmp(facility, "LOCAL5"))
223 chan->facility = LOG_LOCAL5;
224 else if (!strcasecmp(facility, "LOCAL6"))
225 chan->facility = LOG_LOCAL6;
226 else if (!strcasecmp(facility, "LOCAL7"))
227 chan->facility = LOG_LOCAL7;
230 if (0 > chan->facility) {
231 fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
236 chan->type = LOGTYPE_SYSLOG;
237 snprintf(chan->filename, sizeof(chan->filename), "%s", channel);
238 openlog("asterisk", LOG_PID, chan->facility);
240 if (channel[0] == '/') {
241 if(!ast_strlen_zero(hostname)) {
242 snprintf(chan->filename, sizeof(chan->filename) - 1,"%s.%s", channel, hostname);
244 strncpy(chan->filename, channel, sizeof(chan->filename) - 1);
248 if(!ast_strlen_zero(hostname)) {
249 snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s",(char *)ast_config_AST_LOG_DIR, channel, hostname);
251 snprintf(chan->filename, sizeof(chan->filename), "%s/%s", (char *)ast_config_AST_LOG_DIR, channel);
253 chan->fileptr = fopen(chan->filename, "a");
254 if (!chan->fileptr) {
255 /* Can't log here, since we're called with a lock */
256 fprintf(stderr, "Logger Warning: Unable to open log file '%s': %s\n", chan->filename, strerror(errno));
258 chan->type = LOGTYPE_FILE;
260 chan->logmask = make_components(components, lineno);
264 static void init_logger_chain(void)
266 struct logchannel *chan, *cur;
267 struct ast_config *cfg;
268 struct ast_variable *var;
271 /* delete our list of log channels */
272 ast_mutex_lock(&loglock);
280 ast_mutex_unlock(&loglock);
286 cfg = ast_config_load("logger.conf");
288 /* If no config file, we're fine */
292 ast_mutex_lock(&loglock);
293 if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
295 if(gethostname(hostname, sizeof(hostname))) {
296 strncpy(hostname, "unknown", sizeof(hostname)-1);
297 ast_log(LOG_WARNING, "What box has no hostname???\n");
303 if ((s = ast_variable_retrieve(cfg, "general", "dateformat"))) {
304 strncpy(dateformat, s, sizeof(dateformat) - 1);
306 strncpy(dateformat, "%b %e %T", sizeof(dateformat) - 1);
307 if ((s = ast_variable_retrieve(cfg, "general", "queue_log"))) {
308 logfiles.queue_log = ast_true(s);
310 if ((s = ast_variable_retrieve(cfg, "general", "event_log"))) {
311 logfiles.event_log = ast_true(s);
314 var = ast_variable_browse(cfg, "logfiles");
316 chan = make_logchannel(var->name, var->value, var->lineno);
318 chan->next = logchannels;
320 global_logmask |= chan->logmask;
325 ast_config_destroy(cfg);
326 ast_mutex_unlock(&loglock);
329 static FILE *qlog = NULL;
330 AST_MUTEX_DEFINE_STATIC(qloglock);
332 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
335 ast_mutex_lock(&qloglock);
338 fprintf(qlog, "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
339 vfprintf(qlog, fmt, ap);
344 ast_mutex_unlock(&qloglock);
347 static void queue_log_init(void)
352 ast_mutex_lock(&qloglock);
358 snprintf(filename, sizeof(filename), "%s/%s", (char *)ast_config_AST_LOG_DIR, "queue_log");
359 if (logfiles.queue_log) {
360 qlog = fopen(filename, "a");
362 ast_mutex_unlock(&qloglock);
364 ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
366 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
369 int reload_logger(int rotate)
371 char old[AST_CONFIG_MAX_PATH] = "";
372 char new[AST_CONFIG_MAX_PATH];
373 struct logchannel *f;
377 ast_mutex_lock(&loglock);
384 mkdir((char *)ast_config_AST_LOG_DIR, 0755);
385 snprintf(old, sizeof(old), "%s/%s", (char *)ast_config_AST_LOG_DIR, EVENTLOG);
387 if (logfiles.event_log) {
390 snprintf(new, sizeof(new), "%s/%s.%d", (char *)ast_config_AST_LOG_DIR, EVENTLOG,x);
391 myf = fopen((char *)new, "r");
392 if (myf) /* File exists */
400 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
403 eventlog = fopen(old, "a");
409 f->disabled = 0; /* Re-enable logging at reload */
410 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
412 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
413 fclose(f->fileptr); /* Close file */
416 strncpy(old, f->filename, sizeof(old) - 1);
419 snprintf(new, sizeof(new), "%s.%d", f->filename, x);
420 myf = fopen((char *)new, "r");
430 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
436 ast_mutex_unlock(&loglock);
441 if (logfiles.event_log) {
443 ast_log(LOG_EVENT, "Restarted Asterisk Event Logger\n");
445 ast_verbose("Asterisk Event Logger restarted\n");
448 ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
450 pending_logger_reload = 0;
454 static int handle_logger_reload(int fd, int argc, char *argv[])
456 if(reload_logger(0)) {
457 ast_cli(fd, "Failed to reload the logger\n");
458 return RESULT_FAILURE;
460 return RESULT_SUCCESS;
463 static int handle_logger_rotate(int fd, int argc, char *argv[])
465 if(reload_logger(1)) {
466 ast_cli(fd, "Failed to reload the logger and rotate log files\n");
467 return RESULT_FAILURE;
469 return RESULT_SUCCESS;
472 /*--- handle_logger_show_channels: CLI command to show logging system
474 static int handle_logger_show_channels(int fd, int argc, char *argv[])
476 #define FORMATL "%-35.35s %-8.8s %-9.9s "
477 struct logchannel *chan;
479 ast_mutex_lock(&loglock);
482 ast_cli(fd,FORMATL, "Channel", "Type", "Status");
483 ast_cli(fd, "Configuration\n");
484 ast_cli(fd,FORMATL, "-------", "----", "------");
485 ast_cli(fd, "-------------\n");
487 ast_cli(fd, FORMATL, chan->filename, chan->type==LOGTYPE_CONSOLE ? "Console" : (chan->type==LOGTYPE_SYSLOG ? "Syslog" : "File"),
488 chan->disabled ? "Disabled" : "Enabled");
490 if (chan->logmask & (1 << __LOG_DEBUG))
491 ast_cli(fd, "Debug ");
492 if (chan->logmask & (1 << __LOG_VERBOSE))
493 ast_cli(fd, "Verbose ");
494 if (chan->logmask & (1 << __LOG_WARNING))
495 ast_cli(fd, "Warning ");
496 if (chan->logmask & (1 << __LOG_NOTICE))
497 ast_cli(fd, "Notice ");
498 if (chan->logmask & (1 << __LOG_ERROR))
499 ast_cli(fd, "Error ");
500 if (chan->logmask & (1 << __LOG_EVENT))
501 ast_cli(fd, "Event ");
507 ast_mutex_unlock(&loglock);
509 return RESULT_SUCCESS;
513 void (*verboser)(const char *string, int opos, int replacelast, int complete);
518 static char logger_reload_help[] =
519 "Usage: logger reload\n"
520 " Reloads the logger subsystem state. Use after restarting syslogd(8) if you are using syslog logging.\n";
522 static char logger_rotate_help[] =
523 "Usage: logger rotate\n"
524 " Rotates and Reopens the log files.\n";
526 static char logger_show_channels_help[] =
527 "Usage: logger show channels\n"
528 " Show configured logger channels.\n";
530 static struct ast_cli_entry logger_show_channels_cli =
531 { { "logger", "show", "channels", NULL },
532 handle_logger_show_channels, "List configured log channels",
533 logger_show_channels_help };
535 static struct ast_cli_entry reload_logger_cli =
536 { { "logger", "reload", NULL },
537 handle_logger_reload, "Reopens the log files",
538 logger_reload_help };
540 static struct ast_cli_entry rotate_logger_cli =
541 { { "logger", "rotate", NULL },
542 handle_logger_rotate, "Rotates and reopens the log files",
543 logger_rotate_help };
545 static int handle_SIGXFSZ(int sig)
547 /* Indicate need to reload */
548 pending_logger_reload = 1;
552 int init_logger(void)
556 /* auto rotate if sig SIGXFSZ comes a-knockin */
557 (void) signal(SIGXFSZ,(void *) handle_SIGXFSZ);
559 /* register the relaod logger cli command */
560 ast_cli_register(&reload_logger_cli);
561 ast_cli_register(&rotate_logger_cli);
562 ast_cli_register(&logger_show_channels_cli);
564 /* initialize queue logger */
567 /* create log channels */
570 /* create the eventlog */
571 if (logfiles.event_log) {
572 mkdir((char *)ast_config_AST_LOG_DIR, 0755);
573 snprintf(tmp, sizeof(tmp), "%s/%s", (char *)ast_config_AST_LOG_DIR, EVENTLOG);
574 eventlog = fopen((char *)tmp, "a");
576 ast_log(LOG_EVENT, "Started Asterisk Event Logger\n");
578 ast_verbose("Asterisk Event Logger Started %s\n",(char *)tmp);
581 ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
587 void close_logger(void)
589 struct msglist *m, *tmp;
591 ast_mutex_lock(&msglist_lock);
603 ast_mutex_unlock(&msglist_lock);
607 static void strip_coloring(char *str)
609 char *src = str, *dest, *end;
614 /* find the first potential escape sequence in the string */
616 while (*src && (*src != '\033'))
623 /* at the top of this loop, *src will always be an ESC character */
624 if ((src[1] == '[') && ((end = strchr(src + 2, 'm'))))
629 /* copy characters, checking for ESC as we go */
630 while (*src && (*src != '\033'))
637 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, const char *fmt, va_list args)
642 if (level >= SYSLOG_NLEVELS) {
643 /* we are locked here, so cannot ast_log() */
644 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
647 if (level == __LOG_VERBOSE) {
648 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: ", (long)GETTID());
651 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: ",
652 levels[level], (long)GETTID(), file, line, function);
654 s = buf + strlen(buf);
655 vsnprintf(s, sizeof(buf) - strlen(buf), fmt, args);
657 syslog(syslog_level_map[level], "%s", buf);
661 * send log messages to syslog and/or the console
663 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
665 struct logchannel *chan;
673 if (!option_verbose && !option_debug && (level == __LOG_DEBUG)) {
676 /* Ignore anything that never gets logged anywhere */
677 if (!(global_logmask & (1 << level)))
680 /* Ignore anything other than the currently debugged file if there is one */
681 if ((level == __LOG_DEBUG) && !ast_strlen_zero(debug_filename) && strcasecmp(debug_filename, file))
684 /* begin critical section */
685 ast_mutex_lock(&loglock);
688 localtime_r(&t, &tm);
689 strftime(date, sizeof(date), dateformat, &tm);
691 if (logfiles.event_log && level == __LOG_EVENT) {
694 fprintf(eventlog, "%s asterisk[%d]: ", date, getpid());
695 vfprintf(eventlog, fmt, ap);
699 ast_mutex_unlock(&loglock);
705 while(chan && !chan->disabled) {
706 /* Check syslog channels */
707 if (chan->type == LOG_SYSLOG && (chan->logmask & (1 << level))) {
709 ast_log_vsyslog(level, file, line, function, fmt, ap);
711 /* Console channels */
712 } else if ((chan->logmask & (1 << level)) && (chan->type == LOGTYPE_CONSOLE)) {
714 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
716 if (level != __LOG_VERBOSE) {
717 sprintf(linestr, "%d", line);
718 snprintf(buf, sizeof(buf), option_timestamp ? "[%s] %s[%ld]: %s:%s %s: " : "%s %s[%ld]: %s:%s %s: ",
720 term_color(tmp1, levels[level], colors[level], 0, sizeof(tmp1)),
722 term_color(tmp2, file, COLOR_BRWHITE, 0, sizeof(tmp2)),
723 term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
724 term_color(tmp4, function, COLOR_BRWHITE, 0, sizeof(tmp4)));
726 ast_console_puts(buf);
728 vsnprintf(buf, sizeof(buf), fmt, ap);
730 ast_console_puts(buf);
733 } else if ((chan->logmask & (1 << level)) && (chan->fileptr)) {
735 snprintf(buf, sizeof(buf), option_timestamp ? "[%s] %s[%ld]: " : "%s %s[%ld] %s: ", date,
736 levels[level], (long)GETTID(), file);
737 res = fprintf(chan->fileptr, buf);
738 if (res <= 0 && buf[0] != '\0') { /* Error, no characters printed */
739 fprintf(stderr,"**** Asterisk Logging Error: ***********\n");
740 if (errno == ENOMEM || errno == ENOSPC) {
741 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
743 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
744 manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
747 /* No error message, continue printing */
749 vsnprintf(buf, sizeof(buf), fmt, ap);
752 fputs(buf, chan->fileptr);
753 fflush(chan->fileptr);
760 * we don't have the logger chain configured yet,
761 * so just log to stdout
763 if (level != __LOG_VERBOSE) {
765 vsnprintf(buf, sizeof(buf), fmt, ap);
771 ast_mutex_unlock(&loglock);
772 /* end critical section */
773 if (pending_logger_reload) {
775 ast_log(LOG_EVENT,"Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
777 ast_verbose("Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
781 extern void ast_verbose(const char *fmt, ...)
783 static char stuff[4096];
784 static int pos = 0, opos;
785 static int replacelast = 0, complete;
795 ast_mutex_lock(&msglist_lock);
797 localtime_r(&t, &tm);
798 strftime(date, sizeof(date), dateformat, &tm);
800 if (option_timestamp) {
801 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
803 sprintf(datefmt, "[%s] %s", date, fmt);
807 vsnprintf(stuff + pos, sizeof(stuff) - pos, fmt, ap);
812 if (stuff[strlen(stuff)-1] == '\n')
817 if (msgcnt < MAX_MSG_QUEUE) {
818 /* Allocate new structure */
819 m = malloc(sizeof(struct msglist));
822 /* Recycle the oldest entry */
828 m->msg = strdup(stuff);
838 ast_log(LOG_ERROR, "Out of memory\n");
846 v->verboser(stuff, opos, replacelast, complete);
850 fprintf(stdout, stuff + opos); */
851 ast_log(LOG_VERBOSE, "%s", stuff);
853 if (stuff[strlen(stuff)-1] != '\n')
856 replacelast = pos = 0;
860 ast_mutex_unlock(&msglist_lock);
863 int ast_verbose_dmesg(void (*v)(const char *string, int opos, int replacelast, int complete))
866 ast_mutex_lock(&msglist_lock);
869 /* Send all the existing entries that we have queued (i.e. they're likely to have missed) */
873 ast_mutex_unlock(&msglist_lock);
877 int ast_register_verbose(void (*v)(const char *string, int opos, int replacelast, int complete))
881 /* XXX Should be more flexible here, taking > 1 verboser XXX */
882 if ((tmp = malloc(sizeof (struct verb)))) {
884 ast_mutex_lock(&msglist_lock);
885 tmp->next = verboser;
889 /* Send all the existing entries that we have queued (i.e. they're likely to have missed) */
893 ast_mutex_unlock(&msglist_lock);
899 int ast_unregister_verbose(void (*v)(const char *string, int opos, int replacelast, int complete))
902 struct verb *tmp, *tmpl=NULL;
903 ast_mutex_lock(&msglist_lock);
906 if (tmp->verboser == v) {
908 tmpl->next = tmp->next;
910 verboser = tmp->next;
919 ast_mutex_unlock(&msglist_lock);