make DEBUG_THREADS have more visible logging
[asterisk/asterisk.git] / logger.c
1 /*
2  * Asterisk Logger
3  * 
4  * Mark Spencer <markster@marko.net>
5  *
6  * Copyright(C)1999, Linux Support Services, Inc.
7  * 
8  * Distributed under the terms of the GNU General Public License (GPL) Version 2
9  *
10  * Logging routines
11  *
12  */
13
14 #include <signal.h>
15 #include <stdarg.h>
16 #include <stdio.h>
17 #include <unistd.h>
18 #include <time.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <errno.h>
22 #include <sys/stat.h>
23
24 #define SYSLOG_NAMES /* so we can map syslog facilities names to their numeric values,
25                         from <syslog.h> which is included by logger.h */
26 #include <syslog.h>
27
28 #include "asterisk.h"
29
30 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
31
32 static int syslog_level_map[] = {
33         LOG_DEBUG,
34         LOG_INFO,    /* arbitrary equivalent of LOG_EVENT */
35         LOG_NOTICE,
36         LOG_WARNING,
37         LOG_ERR,
38         LOG_DEBUG,
39         LOG_DEBUG
40 };
41
42 #define SYSLOG_NLEVELS 6
43
44 #include "asterisk/logger.h"
45 #include "asterisk/lock.h"
46 #include "asterisk/options.h"
47 #include "asterisk/channel.h"
48 #include "asterisk/config.h"
49 #include "asterisk/term.h"
50 #include "asterisk/cli.h"
51 #include "asterisk/utils.h"
52 #include "asterisk/manager.h"
53
54 #define MAX_MSG_QUEUE 200
55
56 #if defined(__linux__) && defined(__NR_gettid)
57 #include <asm/unistd.h>
58 #define GETTID() syscall(__NR_gettid)
59 #else
60 #define GETTID() getpid()
61 #endif
62
63 static char dateformat[256] = "%b %e %T";               /* Original Asterisk Format */
64
65 AST_MUTEX_DEFINE_STATIC(msglist_lock);
66 AST_MUTEX_DEFINE_STATIC(loglock);
67 static int filesize_reload_needed = 0;
68 static int global_logmask = -1;
69
70 static struct {
71         unsigned int queue_log:1;
72         unsigned int event_log:1;
73 } logfiles = { 1, 1 };
74
75 static struct msglist {
76         char *msg;
77         struct msglist *next;
78 } *list = NULL, *last = NULL;
79
80 static char hostname[MAXHOSTNAMELEN];
81
82 enum logtypes {
83         LOGTYPE_SYSLOG,
84         LOGTYPE_FILE,
85         LOGTYPE_CONSOLE,
86 };
87
88 struct logchannel {
89         int logmask;                    /* What to log to this channel */
90         int disabled;                   /* If this channel is disabled or not */
91         int facility;                   /* syslog facility */
92         enum logtypes type;             /* Type of log channel */
93         FILE *fileptr;                  /* logfile logging file pointer */
94         char filename[256];             /* Filename */
95         struct logchannel *next;        /* Next channel in chain */
96 };
97
98 static struct logchannel *logchannels = NULL;
99
100 static int msgcnt = 0;
101
102 static FILE *eventlog = NULL;
103
104 static char *levels[] = {
105         "DEBUG",
106         "EVENT",
107         "NOTICE",
108         "WARNING",
109         "ERROR",
110         "VERBOSE",
111         "DTMF"
112 };
113
114 static int colors[] = {
115         COLOR_BRGREEN,
116         COLOR_BRBLUE,
117         COLOR_YELLOW,
118         COLOR_BRRED,
119         COLOR_RED,
120         COLOR_GREEN,
121         COLOR_BRGREEN
122 };
123
124 static int make_components(char *s, int lineno)
125 {
126         char *w;
127         int res = 0;
128         char *stringp=NULL;
129         stringp=s;
130         w = strsep(&stringp, ",");
131         while(w) {
132                 while(*w && (*w < 33))
133                         w++;
134                 if (!strcasecmp(w, "error")) 
135                         res |= (1 << __LOG_ERROR);
136                 else if (!strcasecmp(w, "warning"))
137                         res |= (1 << __LOG_WARNING);
138                 else if (!strcasecmp(w, "notice"))
139                         res |= (1 << __LOG_NOTICE);
140                 else if (!strcasecmp(w, "event"))
141                         res |= (1 << __LOG_EVENT);
142                 else if (!strcasecmp(w, "debug"))
143                         res |= (1 << __LOG_DEBUG);
144                 else if (!strcasecmp(w, "verbose"))
145                         res |= (1 << __LOG_VERBOSE);
146                 else if (!strcasecmp(w, "dtmf"))
147                         res |= (1 << __LOG_DTMF);
148                 else {
149                         fprintf(stderr, "Logfile Warning: Unknown keyword '%s' at line %d of logger.conf\n", w, lineno);
150                 }
151                 w = strsep(&stringp, ",");
152         }
153         return res;
154 }
155
156 static struct logchannel *make_logchannel(char *channel, char *components, int lineno)
157 {
158         struct logchannel *chan;
159         char *facility;
160 #ifndef SOLARIS
161         CODE *cptr;
162 #endif
163
164         if (ast_strlen_zero(channel))
165                 return NULL;
166         chan = malloc(sizeof(struct logchannel));
167
168         if (!chan)      /* Can't allocate memory */
169                 return NULL;
170
171         memset(chan, 0, sizeof(struct logchannel));
172         if (!strcasecmp(channel, "console")) {
173                 chan->type = LOGTYPE_CONSOLE;
174         } else if (!strncasecmp(channel, "syslog", 6)) {
175                 /*
176                 * syntax is:
177                 *  syslog.facility => level,level,level
178                 */
179                 facility = strchr(channel, '.');
180                 if(!facility++ || !facility) {
181                         facility = "local0";
182                 }
183
184 #ifndef SOLARIS
185                 /*
186                 * Walk through the list of facilitynames (defined in sys/syslog.h)
187                 * to see if we can find the one we have been given
188                 */
189                 chan->facility = -1;
190                 cptr = facilitynames;
191                 while (cptr->c_name) {
192                         if (!strcasecmp(facility, cptr->c_name)) {
193                                 chan->facility = cptr->c_val;
194                                 break;
195                         }
196                         cptr++;
197                 }
198 #else
199                 chan->facility = -1;
200                 if (!strcasecmp(facility, "kern")) 
201                         chan->facility = LOG_KERN;
202                 else if (!strcasecmp(facility, "USER")) 
203                         chan->facility = LOG_USER;
204                 else if (!strcasecmp(facility, "MAIL")) 
205                         chan->facility = LOG_MAIL;
206                 else if (!strcasecmp(facility, "DAEMON")) 
207                         chan->facility = LOG_DAEMON;
208                 else if (!strcasecmp(facility, "AUTH")) 
209                         chan->facility = LOG_AUTH;
210                 else if (!strcasecmp(facility, "SYSLOG")) 
211                         chan->facility = LOG_SYSLOG;
212                 else if (!strcasecmp(facility, "LPR")) 
213                         chan->facility = LOG_LPR;
214                 else if (!strcasecmp(facility, "NEWS")) 
215                         chan->facility = LOG_NEWS;
216                 else if (!strcasecmp(facility, "UUCP")) 
217                         chan->facility = LOG_UUCP;
218                 else if (!strcasecmp(facility, "CRON")) 
219                         chan->facility = LOG_CRON;
220                 else if (!strcasecmp(facility, "LOCAL0")) 
221                         chan->facility = LOG_LOCAL0;
222                 else if (!strcasecmp(facility, "LOCAL1")) 
223                         chan->facility = LOG_LOCAL1;
224                 else if (!strcasecmp(facility, "LOCAL2")) 
225                         chan->facility = LOG_LOCAL2;
226                 else if (!strcasecmp(facility, "LOCAL3")) 
227                         chan->facility = LOG_LOCAL3;
228                 else if (!strcasecmp(facility, "LOCAL4")) 
229                         chan->facility = LOG_LOCAL4;
230                 else if (!strcasecmp(facility, "LOCAL5")) 
231                         chan->facility = LOG_LOCAL5;
232                 else if (!strcasecmp(facility, "LOCAL6")) 
233                         chan->facility = LOG_LOCAL6;
234                 else if (!strcasecmp(facility, "LOCAL7")) 
235                         chan->facility = LOG_LOCAL7;
236 #endif /* Solaris */
237
238                 if (0 > chan->facility) {
239                         fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
240                         free(chan);
241                         return NULL;
242                 }
243
244                 chan->type = LOGTYPE_SYSLOG;
245                 snprintf(chan->filename, sizeof(chan->filename), "%s", channel);
246                 openlog("asterisk", LOG_PID, chan->facility);
247         } else {
248                 if (channel[0] == '/') {
249                         if(!ast_strlen_zero(hostname)) { 
250                                 snprintf(chan->filename, sizeof(chan->filename) - 1,"%s.%s", channel, hostname);
251                         } else {
252                                 ast_copy_string(chan->filename, channel, sizeof(chan->filename));
253                         }
254                 }                 
255                 
256                 if(!ast_strlen_zero(hostname)) {
257                         snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s",(char *)ast_config_AST_LOG_DIR, channel, hostname);
258                 } else {
259                         snprintf(chan->filename, sizeof(chan->filename), "%s/%s", (char *)ast_config_AST_LOG_DIR, channel);
260                 }
261                 chan->fileptr = fopen(chan->filename, "a");
262                 if (!chan->fileptr) {
263                         /* Can't log here, since we're called with a lock */
264                         fprintf(stderr, "Logger Warning: Unable to open log file '%s': %s\n", chan->filename, strerror(errno));
265                 } 
266                 chan->type = LOGTYPE_FILE;
267         }
268         chan->logmask = make_components(components, lineno);
269         return chan;
270 }
271
272 static void init_logger_chain(void)
273 {
274         struct logchannel *chan, *cur;
275         struct ast_config *cfg;
276         struct ast_variable *var;
277         char *s;
278
279         /* delete our list of log channels */
280         ast_mutex_lock(&loglock);
281         chan = logchannels;
282         while (chan) {
283                 cur = chan->next;
284                 free(chan);
285                 chan = cur;
286         }
287         logchannels = NULL;
288         ast_mutex_unlock(&loglock);
289         
290         global_logmask = 0;
291         /* close syslog */
292         closelog();
293         
294         cfg = ast_config_load("logger.conf");
295         
296         /* If no config file, we're fine */
297         if (!cfg)
298                 return;
299         
300         ast_mutex_lock(&loglock);
301         if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
302                 if(ast_true(s)) {
303                         if(gethostname(hostname, sizeof(hostname)-1)) {
304                                 ast_copy_string(hostname, "unknown", sizeof(hostname));
305                                 ast_log(LOG_WARNING, "What box has no hostname???\n");
306                         }
307                 } else
308                         hostname[0] = '\0';
309         } else
310                 hostname[0] = '\0';
311         if ((s = ast_variable_retrieve(cfg, "general", "dateformat"))) {
312                 ast_copy_string(dateformat, s, sizeof(dateformat));
313         } else
314                 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
315         if ((s = ast_variable_retrieve(cfg, "general", "queue_log"))) {
316                 logfiles.queue_log = ast_true(s);
317         }
318         if ((s = ast_variable_retrieve(cfg, "general", "event_log"))) {
319                 logfiles.event_log = ast_true(s);
320         }
321
322         var = ast_variable_browse(cfg, "logfiles");
323         while(var) {
324                 chan = make_logchannel(var->name, var->value, var->lineno);
325                 if (chan) {
326                         chan->next = logchannels;
327                         logchannels = chan;
328                         global_logmask |= chan->logmask;
329                 }
330                 var = var->next;
331         }
332
333         ast_config_destroy(cfg);
334         ast_mutex_unlock(&loglock);
335 }
336
337 static FILE *qlog = NULL;
338 AST_MUTEX_DEFINE_STATIC(qloglock);
339
340 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
341 {
342         va_list ap;
343         ast_mutex_lock(&qloglock);
344         if (qlog) {
345                 va_start(ap, fmt);
346                 fprintf(qlog, "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
347                 vfprintf(qlog, fmt, ap);
348                 fprintf(qlog, "\n");
349                 va_end(ap);
350                 fflush(qlog);
351         }
352         ast_mutex_unlock(&qloglock);
353 }
354
355 static void queue_log_init(void)
356 {
357         char filename[256];
358         int reloaded = 0;
359
360         ast_mutex_lock(&qloglock);
361         if (qlog) {
362                 reloaded = 1;
363                 fclose(qlog);
364                 qlog = NULL;
365         }
366         snprintf(filename, sizeof(filename), "%s/%s", (char *)ast_config_AST_LOG_DIR, "queue_log");
367         if (logfiles.queue_log) {
368                 qlog = fopen(filename, "a");
369         }
370         ast_mutex_unlock(&qloglock);
371         if (reloaded) 
372                 ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
373         else
374                 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
375 }
376
377 int reload_logger(int rotate)
378 {
379         char old[AST_CONFIG_MAX_PATH] = "";
380         char new[AST_CONFIG_MAX_PATH];
381         struct logchannel *f;
382         FILE *myf;
383         int x;
384
385         ast_mutex_lock(&loglock);
386         if (eventlog) 
387                 fclose(eventlog);
388         else 
389                 rotate = 0;
390         eventlog = NULL;
391
392         mkdir((char *)ast_config_AST_LOG_DIR, 0755);
393         snprintf(old, sizeof(old), "%s/%s", (char *)ast_config_AST_LOG_DIR, EVENTLOG);
394
395         if (logfiles.event_log) {
396                 if (rotate) {
397                         for (x=0;;x++) {
398                                 snprintf(new, sizeof(new), "%s/%s.%d", (char *)ast_config_AST_LOG_DIR, EVENTLOG,x);
399                                 myf = fopen((char *)new, "r");
400                                 if (myf)        /* File exists */
401                                         fclose(myf);
402                                 else
403                                         break;
404                         }
405         
406                         /* do it */
407                         if (rename(old,new))
408                                 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
409                 }
410
411                 eventlog = fopen(old, "a");
412         }
413
414         f = logchannels;
415         while(f) {
416                 if (f->disabled) {
417                         f->disabled = 0;        /* Re-enable logging at reload */
418                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
419                 }
420                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
421                         fclose(f->fileptr);     /* Close file */
422                         f->fileptr = NULL;
423                         if(rotate) {
424                                 ast_copy_string(old, f->filename, sizeof(old));
425         
426                                 for(x=0;;x++) {
427                                         snprintf(new, sizeof(new), "%s.%d", f->filename, x);
428                                         myf = fopen((char *)new, "r");
429                                         if (myf) {
430                                                 fclose(myf);
431                                         } else {
432                                                 break;
433                                         }
434                                 }
435             
436                                 /* do it */
437                                 if (rename(old,new))
438                                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
439                         }
440                 }
441                 f = f->next;
442         }
443
444         ast_mutex_unlock(&loglock);
445
446         filesize_reload_needed = 0;
447
448         queue_log_init();
449         init_logger_chain();
450
451         if (logfiles.event_log) {
452                 if (eventlog) {
453                         ast_log(LOG_EVENT, "Restarted Asterisk Event Logger\n");
454                         if (option_verbose)
455                                 ast_verbose("Asterisk Event Logger restarted\n");
456                         return 0;
457                 } else 
458                         ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
459         } else 
460                 return 0;
461         return -1;
462 }
463
464 static int handle_logger_reload(int fd, int argc, char *argv[])
465 {
466         if(reload_logger(0)) {
467                 ast_cli(fd, "Failed to reload the logger\n");
468                 return RESULT_FAILURE;
469         } else
470                 return RESULT_SUCCESS;
471 }
472
473 static int handle_logger_rotate(int fd, int argc, char *argv[])
474 {
475         if(reload_logger(1)) {
476                 ast_cli(fd, "Failed to reload the logger and rotate log files\n");
477                 return RESULT_FAILURE;
478         } else
479                 return RESULT_SUCCESS;
480 }
481
482 /*--- handle_logger_show_channels: CLI command to show logging system 
483         configuration */
484 static int handle_logger_show_channels(int fd, int argc, char *argv[])
485 {
486 #define FORMATL "%-35.35s %-8.8s %-9.9s "
487         struct logchannel *chan;
488
489         ast_mutex_lock(&loglock);
490
491         chan = logchannels;
492         ast_cli(fd,FORMATL, "Channel", "Type", "Status");
493         ast_cli(fd, "Configuration\n");
494         ast_cli(fd,FORMATL, "-------", "----", "------");
495         ast_cli(fd, "-------------\n");
496         while (chan) {
497                 ast_cli(fd, FORMATL, chan->filename, chan->type==LOGTYPE_CONSOLE ? "Console" : (chan->type==LOGTYPE_SYSLOG ? "Syslog" : "File"),
498                         chan->disabled ? "Disabled" : "Enabled");
499                 ast_cli(fd, " - ");
500                 if (chan->logmask & (1 << __LOG_DEBUG)) 
501                         ast_cli(fd, "Debug ");
502                 if (chan->logmask & (1 << __LOG_DTMF)) 
503                         ast_cli(fd, "DTMF ");
504                 if (chan->logmask & (1 << __LOG_VERBOSE)) 
505                         ast_cli(fd, "Verbose ");
506                 if (chan->logmask & (1 << __LOG_WARNING)) 
507                         ast_cli(fd, "Warning ");
508                 if (chan->logmask & (1 << __LOG_NOTICE)) 
509                         ast_cli(fd, "Notice ");
510                 if (chan->logmask & (1 << __LOG_ERROR)) 
511                         ast_cli(fd, "Error ");
512                 if (chan->logmask & (1 << __LOG_EVENT)) 
513                         ast_cli(fd, "Event ");
514                 ast_cli(fd, "\n");
515                 chan = chan->next;
516         }
517         ast_cli(fd, "\n");
518
519         ast_mutex_unlock(&loglock);
520                 
521         return RESULT_SUCCESS;
522 }
523
524 static struct verb {
525         void (*verboser)(const char *string, int opos, int replacelast, int complete);
526         struct verb *next;
527 } *verboser = NULL;
528
529
530 static char logger_reload_help[] =
531 "Usage: logger reload\n"
532 "       Reloads the logger subsystem state.  Use after restarting syslogd(8) if you are using syslog logging.\n";
533
534 static char logger_rotate_help[] =
535 "Usage: logger rotate\n"
536 "       Rotates and Reopens the log files.\n";
537
538 static char logger_show_channels_help[] =
539 "Usage: logger show channels\n"
540 "       Show configured logger channels.\n";
541
542 static struct ast_cli_entry logger_show_channels_cli = 
543         { { "logger", "show", "channels", NULL }, 
544         handle_logger_show_channels, "List configured log channels",
545         logger_show_channels_help };
546
547 static struct ast_cli_entry reload_logger_cli = 
548         { { "logger", "reload", NULL }, 
549         handle_logger_reload, "Reopens the log files",
550         logger_reload_help };
551
552 static struct ast_cli_entry rotate_logger_cli = 
553         { { "logger", "rotate", NULL }, 
554         handle_logger_rotate, "Rotates and reopens the log files",
555         logger_rotate_help };
556
557 static int handle_SIGXFSZ(int sig) 
558 {
559         /* Indicate need to reload */
560         filesize_reload_needed = 1;
561         return 0;
562 }
563
564 int init_logger(void)
565 {
566         char tmp[256];
567
568         /* auto rotate if sig SIGXFSZ comes a-knockin */
569         (void) signal(SIGXFSZ,(void *) handle_SIGXFSZ);
570
571         /* register the relaod logger cli command */
572         ast_cli_register(&reload_logger_cli);
573         ast_cli_register(&rotate_logger_cli);
574         ast_cli_register(&logger_show_channels_cli);
575
576         /* initialize queue logger */
577         queue_log_init();
578
579         /* create log channels */
580         init_logger_chain();
581
582         /* create the eventlog */
583         if (logfiles.event_log) {
584                 mkdir((char *)ast_config_AST_LOG_DIR, 0755);
585                 snprintf(tmp, sizeof(tmp), "%s/%s", (char *)ast_config_AST_LOG_DIR, EVENTLOG);
586                 eventlog = fopen((char *)tmp, "a");
587                 if (eventlog) {
588                         ast_log(LOG_EVENT, "Started Asterisk Event Logger\n");
589                         if (option_verbose)
590                                 ast_verbose("Asterisk Event Logger Started %s\n",(char *)tmp);
591                         return 0;
592                 } else 
593                         ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
594         } else
595                 return 0;
596
597         return -1;
598 }
599
600 void close_logger(void)
601 {
602         struct msglist *m, *tmp;
603
604         ast_mutex_lock(&msglist_lock);
605         m = list;
606         while(m) {
607                 if (m->msg) {
608                         free(m->msg);
609                 }
610                 tmp = m->next;
611                 free(m);
612                 m = tmp;
613         }
614         list = last = NULL;
615         msgcnt = 0;
616         ast_mutex_unlock(&msglist_lock);
617         return;
618 }
619
620 static void strip_coloring(char *str)
621 {
622         char *src, *dest, *end;
623         
624         if (!str)
625                 return;
626
627         /* find the first potential escape sequence in the string */
628
629         src = strchr(str, '\033');
630         if (!src)
631                 return;
632
633         dest = src;
634         while (*src) {
635                 /* at the top of this loop, *src will always be an ESC character */
636                 if ((src[1] == '[') && ((end = strchr(src + 2, 'm'))))
637                         src = end + 1;
638                 else
639                         *dest++ = *src++;
640
641                 /* copy characters, checking for ESC as we go */
642                 while (*src && (*src != '\033'))
643                         *dest++ = *src++;
644         }
645
646         *dest = '\0';
647 }
648
649 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, const char *fmt, va_list args) 
650 {
651         char buf[BUFSIZ];
652         char *s;
653
654         if (level >= SYSLOG_NLEVELS) {
655                 /* we are locked here, so cannot ast_log() */
656                 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
657                 return;
658         }
659         if (level == __LOG_VERBOSE) {
660                 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: ", (long)GETTID());
661                 level = __LOG_DEBUG;
662         } else if (level == __LOG_DTMF) {
663                 snprintf(buf, sizeof(buf), "DTMF[%ld]: ", (long)GETTID());
664                 level = __LOG_DEBUG;
665         } else {
666                 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: ",
667                          levels[level], (long)GETTID(), file, line, function);
668         }
669         s = buf + strlen(buf);
670         vsnprintf(s, sizeof(buf) - strlen(buf), fmt, args);
671         strip_coloring(s);
672         syslog(syslog_level_map[level], "%s", buf);
673 }
674
675 /*
676  * send log messages to syslog and/or the console
677  */
678 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
679 {
680         struct logchannel *chan;
681         char buf[BUFSIZ];
682         time_t t;
683         struct tm tm;
684         char date[256];
685
686         va_list ap;
687         
688         /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
689            are non-zero; LOG_DEBUG messages can still be displayed if option_debug
690            is zero, if option_verbose is non-zero (this allows for 'level zero'
691            LOG_DEBUG messages to be displayed, if the logmask on any channel
692            allows it)
693         */
694         if (!option_verbose && !option_debug && (level == __LOG_DEBUG)) {
695                 return;
696         }
697
698         /* Ignore anything that never gets logged anywhere */
699         if (!(global_logmask & (1 << level)))
700                 return;
701         
702         /* Ignore anything other than the currently debugged file if there is one */
703         if ((level == __LOG_DEBUG) && !ast_strlen_zero(debug_filename) && strcasecmp(debug_filename, file))
704                 return;
705
706         /* begin critical section */
707         ast_mutex_lock(&loglock);
708
709         time(&t);
710         localtime_r(&t, &tm);
711         strftime(date, sizeof(date), dateformat, &tm);
712
713         if (logfiles.event_log && level == __LOG_EVENT) {
714                 va_start(ap, fmt);
715
716                 fprintf(eventlog, "%s asterisk[%d]: ", date, getpid());
717                 vfprintf(eventlog, fmt, ap);
718                 fflush(eventlog);
719
720                 va_end(ap);
721                 ast_mutex_unlock(&loglock);
722                 return;
723         }
724
725         if (logchannels) {
726                 chan = logchannels;
727                 while(chan && !chan->disabled) {
728                         /* Check syslog channels */
729                         if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << level))) {
730                                 va_start(ap, fmt);
731                                 ast_log_vsyslog(level, file, line, function, fmt, ap);
732                                 va_end(ap);
733                         /* Console channels */
734                         } else if ((chan->logmask & (1 << level)) && (chan->type == LOGTYPE_CONSOLE)) {
735                                 char linestr[128];
736                                 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
737
738                                 if (level != __LOG_VERBOSE) {
739                                         sprintf(linestr, "%d", line);
740                                         snprintf(buf, sizeof(buf), option_timestamp ? "[%s] %s[%ld]: %s:%s %s: " : "%s %s[%ld]: %s:%s %s: ",
741                                                 date,
742                                                 term_color(tmp1, levels[level], colors[level], 0, sizeof(tmp1)),
743                                                 (long)GETTID(),
744                                                 term_color(tmp2, file, COLOR_BRWHITE, 0, sizeof(tmp2)),
745                                                 term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
746                                                 term_color(tmp4, function, COLOR_BRWHITE, 0, sizeof(tmp4)));
747                                         
748                                         ast_console_puts(buf);
749                                         va_start(ap, fmt);
750                                         vsnprintf(buf, sizeof(buf), fmt, ap);
751                                         va_end(ap);
752                                         ast_console_puts(buf);
753                                 }
754                         /* File channels */
755                         } else if ((chan->logmask & (1 << level)) && (chan->fileptr)) {
756                                 int res;
757                                 snprintf(buf, sizeof(buf), option_timestamp ? "[%s] %s[%ld]: " : "%s %s[%ld] %s: ", date,
758                                         levels[level], (long)GETTID(), file);
759                                 res = fprintf(chan->fileptr, buf);
760                                 if (res <= 0 && buf[0] != '\0') {       /* Error, no characters printed */
761                                         fprintf(stderr,"**** Asterisk Logging Error: ***********\n");
762                                         if (errno == ENOMEM || errno == ENOSPC) {
763                                                 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
764                                         } else
765                                                 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
766                                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
767                                         chan->disabled = 1;     
768                                 } else {
769                                         /* No error message, continue printing */
770                                         va_start(ap, fmt);
771                                         vsnprintf(buf, sizeof(buf), fmt, ap);
772                                         va_end(ap);
773                                         strip_coloring(buf);
774                                         fputs(buf, chan->fileptr);
775                                         fflush(chan->fileptr);
776                                 }
777                         }
778                         chan = chan->next;
779                 }
780         } else {
781                 /* 
782                  * we don't have the logger chain configured yet,
783                  * so just log to stdout 
784                 */
785                 if (level != __LOG_VERBOSE) {
786                         va_start(ap, fmt);
787                         vsnprintf(buf, sizeof(buf), fmt, ap);
788                         va_end(ap);
789                         fputs(buf, stdout);
790                 }
791         }
792
793         ast_mutex_unlock(&loglock);
794         /* end critical section */
795         if (filesize_reload_needed) {
796                 reload_logger(1);
797                 ast_log(LOG_EVENT,"Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
798                 if (option_verbose)
799                         ast_verbose("Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
800         }
801 }
802
803 extern void ast_verbose(const char *fmt, ...)
804 {
805         static char stuff[4096];
806         static int pos = 0, opos;
807         static int replacelast = 0, complete;
808         struct msglist *m;
809         struct verb *v;
810         time_t t;
811         struct tm tm;
812         char date[40];
813         char *datefmt;
814         
815         va_list ap;
816         va_start(ap, fmt);
817         ast_mutex_lock(&msglist_lock);
818         time(&t);
819         localtime_r(&t, &tm);
820         strftime(date, sizeof(date), dateformat, &tm);
821
822         if (option_timestamp) {
823                 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
824                 if (datefmt) {
825                         sprintf(datefmt, "[%s] %s", date, fmt);
826                         fmt = datefmt;
827                 }
828         }
829         vsnprintf(stuff + pos, sizeof(stuff) - pos, fmt, ap);
830         opos = pos;
831         pos = strlen(stuff);
832
833
834         if (stuff[strlen(stuff)-1] == '\n') 
835                 complete = 1;
836         else
837                 complete=0;
838         if (complete) {
839                 if (msgcnt < MAX_MSG_QUEUE) {
840                         /* Allocate new structure */
841                         m = malloc(sizeof(struct msglist));
842                         msgcnt++;
843                 } else {
844                         /* Recycle the oldest entry */
845                         m = list;
846                         list = list->next;
847                         free(m->msg);
848                 }
849                 if (m) {
850                         m->msg = strdup(stuff);
851                         if (m->msg) {
852                                 if (last)
853                                         last->next = m;
854                                 else
855                                         list = m;
856                                 m->next = NULL;
857                                 last = m;
858                         } else {
859                                 msgcnt--;
860                                 ast_log(LOG_ERROR, "Out of memory\n");
861                                 free(m);
862                         }
863                 }
864         }
865         if (verboser) {
866                 v = verboser;
867                 while(v) {
868                         v->verboser(stuff, opos, replacelast, complete);
869                         v = v->next;
870                 }
871         } /* else
872                 fprintf(stdout, stuff + opos); */
873         ast_log(LOG_VERBOSE, "%s", stuff);
874         if (strlen(stuff)) {
875                 if (stuff[strlen(stuff)-1] != '\n') 
876                         replacelast = 1;
877                 else 
878                         replacelast = pos = 0;
879         }
880         va_end(ap);
881
882         ast_mutex_unlock(&msglist_lock);
883 }
884
885 int ast_verbose_dmesg(void (*v)(const char *string, int opos, int replacelast, int complete))
886 {
887         struct msglist *m;
888         ast_mutex_lock(&msglist_lock);
889         m = list;
890         while(m) {
891                 /* Send all the existing entries that we have queued (i.e. they're likely to have missed) */
892                 v(m->msg, 0, 0, 1);
893                 m = m->next;
894         }
895         ast_mutex_unlock(&msglist_lock);
896         return 0;
897 }
898
899 int ast_register_verbose(void (*v)(const char *string, int opos, int replacelast, int complete)) 
900 {
901         struct msglist *m;
902         struct verb *tmp;
903         /* XXX Should be more flexible here, taking > 1 verboser XXX */
904         if ((tmp = malloc(sizeof (struct verb)))) {
905                 tmp->verboser = v;
906                 ast_mutex_lock(&msglist_lock);
907                 tmp->next = verboser;
908                 verboser = tmp;
909                 m = list;
910                 while(m) {
911                         /* Send all the existing entries that we have queued (i.e. they're likely to have missed) */
912                         v(m->msg, 0, 0, 1);
913                         m = m->next;
914                 }
915                 ast_mutex_unlock(&msglist_lock);
916                 return 0;
917         }
918         return -1;
919 }
920
921 int ast_unregister_verbose(void (*v)(const char *string, int opos, int replacelast, int complete))
922 {
923         int res = -1;
924         struct verb *tmp, *tmpl=NULL;
925         ast_mutex_lock(&msglist_lock);
926         tmp = verboser;
927         while(tmp) {
928                 if (tmp->verboser == v) {
929                         if (tmpl)
930                                 tmpl->next = tmp->next;
931                         else
932                                 verboser = tmp->next;
933                         free(tmp);
934                         break;
935                 }
936                 tmpl = tmp;
937                 tmp = tmp->next;
938         }
939         if (tmp)
940                 res = 0;
941         ast_mutex_unlock(&msglist_lock);
942         return res;
943 }