Fri Jan 29 14:25:16 2010

Asterisk developer's documentation


logger.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Asterisk Logger
00022  * 
00023  * Logging routines
00024  *
00025  * \author Mark Spencer <markster@digium.com>
00026  */
00027 
00028 #include "asterisk.h"
00029 
00030 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 193193 $")
00031 
00032 #include <signal.h>
00033 #include <stdarg.h>
00034 #include <stdio.h>
00035 #include <unistd.h>
00036 #include <time.h>
00037 #include <string.h>
00038 #include <stdlib.h>
00039 #include <errno.h>
00040 #include <sys/stat.h>
00041 #if ((defined(AST_DEVMODE)) && (defined(linux)))
00042 #include <execinfo.h>
00043 #define MAX_BACKTRACE_FRAMES 20
00044 #endif
00045 
00046 #define SYSLOG_NAMES /* so we can map syslog facilities names to their numeric values,
00047               from <syslog.h> which is included by logger.h */
00048 #include <syslog.h>
00049 
00050 static int syslog_level_map[] = {
00051    LOG_DEBUG,
00052    LOG_INFO,    /* arbitrary equivalent of LOG_EVENT */
00053    LOG_NOTICE,
00054    LOG_WARNING,
00055    LOG_ERR,
00056    LOG_DEBUG,
00057    LOG_DEBUG
00058 };
00059 
00060 #define SYSLOG_NLEVELS sizeof(syslog_level_map) / sizeof(int)
00061 
00062 #include "asterisk/logger.h"
00063 #include "asterisk/lock.h"
00064 #include "asterisk/options.h"
00065 #include "asterisk/channel.h"
00066 #include "asterisk/config.h"
00067 #include "asterisk/term.h"
00068 #include "asterisk/cli.h"
00069 #include "asterisk/utils.h"
00070 #include "asterisk/manager.h"
00071 #include "asterisk/threadstorage.h"
00072 
00073 #if defined(__linux__) && !defined(__NR_gettid)
00074 #include <asm/unistd.h>
00075 #endif
00076 
00077 #if defined(__linux__) && defined(__NR_gettid)
00078 #define GETTID() syscall(__NR_gettid)
00079 #else
00080 #define GETTID() getpid()
00081 #endif
00082 
00083 
00084 static char dateformat[256] = "%b %e %T";    /* Original Asterisk Format */
00085 
00086 static int filesize_reload_needed;
00087 static int global_logmask = -1;
00088 
00089 static struct {
00090    unsigned int queue_log:1;
00091    unsigned int event_log:1;
00092 } logfiles = { 1, 1 };
00093 
00094 static char hostname[MAXHOSTNAMELEN];
00095 
00096 enum logtypes {
00097    LOGTYPE_SYSLOG,
00098    LOGTYPE_FILE,
00099    LOGTYPE_CONSOLE,
00100 };
00101 
00102 struct logchannel {
00103    int logmask;         /* What to log to this channel */
00104    int disabled;        /* If this channel is disabled or not */
00105    int facility;        /* syslog facility */
00106    enum logtypes type;     /* Type of log channel */
00107    FILE *fileptr;       /* logfile logging file pointer */
00108    char filename[256];     /* Filename */
00109    AST_LIST_ENTRY(logchannel) list;
00110 };
00111 
00112 static AST_LIST_HEAD_STATIC(logchannels, logchannel);
00113 
00114 static FILE *eventlog;
00115 static FILE *qlog;
00116 
00117 static char *levels[] = {
00118    "DEBUG",
00119    "EVENT",
00120    "NOTICE",
00121    "WARNING",
00122    "ERROR",
00123    "VERBOSE",
00124    "DTMF"
00125 };
00126 
00127 static int colors[] = {
00128    COLOR_BRGREEN,
00129    COLOR_BRBLUE,
00130    COLOR_YELLOW,
00131    COLOR_BRRED,
00132    COLOR_RED,
00133    COLOR_GREEN,
00134    COLOR_BRGREEN
00135 };
00136 
00137 AST_THREADSTORAGE(verbose_buf, verbose_buf_init);
00138 #define VERBOSE_BUF_INIT_SIZE   128
00139 
00140 AST_THREADSTORAGE(log_buf, log_buf_init);
00141 #define LOG_BUF_INIT_SIZE       128
00142 
00143 static int make_components(char *s, int lineno)
00144 {
00145    char *w;
00146    int res = 0;
00147    char *stringp = s;
00148 
00149    while ((w = strsep(&stringp, ","))) {
00150       w = ast_skip_blanks(w);
00151       if (!strcasecmp(w, "error")) 
00152          res |= (1 << __LOG_ERROR);
00153       else if (!strcasecmp(w, "warning"))
00154          res |= (1 << __LOG_WARNING);
00155       else if (!strcasecmp(w, "notice"))
00156          res |= (1 << __LOG_NOTICE);
00157       else if (!strcasecmp(w, "event"))
00158          res |= (1 << __LOG_EVENT);
00159       else if (!strcasecmp(w, "debug"))
00160          res |= (1 << __LOG_DEBUG);
00161       else if (!strcasecmp(w, "verbose"))
00162          res |= (1 << __LOG_VERBOSE);
00163       else if (!strcasecmp(w, "dtmf"))
00164          res |= (1 << __LOG_DTMF);
00165       else {
00166          fprintf(stderr, "Logfile Warning: Unknown keyword '%s' at line %d of logger.conf\n", w, lineno);
00167       }
00168    }
00169 
00170    return res;
00171 }
00172 
00173 static struct logchannel *make_logchannel(char *channel, char *components, int lineno)
00174 {
00175    struct logchannel *chan;
00176    char *facility;
00177 #ifndef SOLARIS
00178    CODE *cptr;
00179 #endif
00180 
00181    if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan))))
00182       return NULL;
00183 
00184    if (!strcasecmp(channel, "console")) {
00185       chan->type = LOGTYPE_CONSOLE;
00186    } else if (!strncasecmp(channel, "syslog", 6)) {
00187       /*
00188       * syntax is:
00189       *  syslog.facility => level,level,level
00190       */
00191       facility = strchr(channel, '.');
00192       if(!facility++ || !facility) {
00193          facility = "local0";
00194       }
00195 
00196 #ifndef SOLARIS
00197       /*
00198       * Walk through the list of facilitynames (defined in sys/syslog.h)
00199       * to see if we can find the one we have been given
00200       */
00201       chan->facility = -1;
00202       cptr = facilitynames;
00203       while (cptr->c_name) {
00204          if (!strcasecmp(facility, cptr->c_name)) {
00205             chan->facility = cptr->c_val;
00206             break;
00207          }
00208          cptr++;
00209       }
00210 #else
00211       chan->facility = -1;
00212       if (!strcasecmp(facility, "kern")) 
00213          chan->facility = LOG_KERN;
00214       else if (!strcasecmp(facility, "USER")) 
00215          chan->facility = LOG_USER;
00216       else if (!strcasecmp(facility, "MAIL")) 
00217          chan->facility = LOG_MAIL;
00218       else if (!strcasecmp(facility, "DAEMON")) 
00219          chan->facility = LOG_DAEMON;
00220       else if (!strcasecmp(facility, "AUTH")) 
00221          chan->facility = LOG_AUTH;
00222       else if (!strcasecmp(facility, "SYSLOG")) 
00223          chan->facility = LOG_SYSLOG;
00224       else if (!strcasecmp(facility, "LPR")) 
00225          chan->facility = LOG_LPR;
00226       else if (!strcasecmp(facility, "NEWS")) 
00227          chan->facility = LOG_NEWS;
00228       else if (!strcasecmp(facility, "UUCP")) 
00229          chan->facility = LOG_UUCP;
00230       else if (!strcasecmp(facility, "CRON")) 
00231          chan->facility = LOG_CRON;
00232       else if (!strcasecmp(facility, "LOCAL0")) 
00233          chan->facility = LOG_LOCAL0;
00234       else if (!strcasecmp(facility, "LOCAL1")) 
00235          chan->facility = LOG_LOCAL1;
00236       else if (!strcasecmp(facility, "LOCAL2")) 
00237          chan->facility = LOG_LOCAL2;
00238       else if (!strcasecmp(facility, "LOCAL3")) 
00239          chan->facility = LOG_LOCAL3;
00240       else if (!strcasecmp(facility, "LOCAL4")) 
00241          chan->facility = LOG_LOCAL4;
00242       else if (!strcasecmp(facility, "LOCAL5")) 
00243          chan->facility = LOG_LOCAL5;
00244       else if (!strcasecmp(facility, "LOCAL6")) 
00245          chan->facility = LOG_LOCAL6;
00246       else if (!strcasecmp(facility, "LOCAL7")) 
00247          chan->facility = LOG_LOCAL7;
00248 #endif /* Solaris */
00249 
00250       if (0 > chan->facility) {
00251          fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
00252          free(chan);
00253          return NULL;
00254       }
00255 
00256       chan->type = LOGTYPE_SYSLOG;
00257       snprintf(chan->filename, sizeof(chan->filename), "%s", channel);
00258       openlog("asterisk", LOG_PID, chan->facility);
00259    } else {
00260       if (!ast_strlen_zero(hostname)) {
00261          snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s",
00262              channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel, hostname);
00263       } else {
00264          snprintf(chan->filename, sizeof(chan->filename), "%s/%s",
00265              channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel);
00266       }
00267       chan->fileptr = fopen(chan->filename, "a");
00268       if (!chan->fileptr) {
00269          /* Can't log here, since we're called with a lock */
00270          fprintf(stderr, "Logger Warning: Unable to open log file '%s': %s\n", chan->filename, strerror(errno));
00271       } 
00272       chan->type = LOGTYPE_FILE;
00273    }
00274    chan->logmask = make_components(components, lineno);
00275    return chan;
00276 }
00277 
00278 static void init_logger_chain(void)
00279 {
00280    struct logchannel *chan;
00281    struct ast_config *cfg;
00282    struct ast_variable *var;
00283    const char *s;
00284 
00285    /* delete our list of log channels */
00286    AST_LIST_LOCK(&logchannels);
00287    while ((chan = AST_LIST_REMOVE_HEAD(&logchannels, list)))
00288       free(chan);
00289    AST_LIST_UNLOCK(&logchannels);
00290    
00291    global_logmask = 0;
00292    errno = 0;
00293    /* close syslog */
00294    closelog();
00295    
00296    cfg = ast_config_load("logger.conf");
00297    
00298    /* If no config file, we're fine, set default options. */
00299    if (!cfg) {
00300       if (errno)
00301          fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
00302       else
00303          fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
00304       if (!(chan = ast_calloc(1, sizeof(*chan))))
00305          return;
00306       chan->type = LOGTYPE_CONSOLE;
00307       chan->logmask = 28; /*warning,notice,error */
00308       AST_LIST_LOCK(&logchannels);
00309       AST_LIST_INSERT_HEAD(&logchannels, chan, list);
00310       AST_LIST_UNLOCK(&logchannels);
00311       global_logmask |= chan->logmask;
00312       return;
00313    }
00314    
00315    if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
00316       if (ast_true(s)) {
00317          if (gethostname(hostname, sizeof(hostname) - 1)) {
00318             ast_copy_string(hostname, "unknown", sizeof(hostname));
00319             ast_log(LOG_WARNING, "What box has no hostname???\n");
00320          }
00321       } else
00322          hostname[0] = '\0';
00323    } else
00324       hostname[0] = '\0';
00325    if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
00326       ast_copy_string(dateformat, s, sizeof(dateformat));
00327    else
00328       ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
00329    if ((s = ast_variable_retrieve(cfg, "general", "queue_log")))
00330       logfiles.queue_log = ast_true(s);
00331    if ((s = ast_variable_retrieve(cfg, "general", "event_log")))
00332       logfiles.event_log = ast_true(s);
00333 
00334    AST_LIST_LOCK(&logchannels);
00335    var = ast_variable_browse(cfg, "logfiles");
00336    for (; var; var = var->next) {
00337       if (!(chan = make_logchannel(var->name, var->value, var->lineno)))
00338          continue;
00339       AST_LIST_INSERT_HEAD(&logchannels, chan, list);
00340       global_logmask |= chan->logmask;
00341    }
00342    AST_LIST_UNLOCK(&logchannels);
00343 
00344    ast_config_destroy(cfg);
00345 }
00346 
00347 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
00348 {
00349    va_list ap;
00350    AST_LIST_LOCK(&logchannels);
00351    if (qlog) {
00352       va_start(ap, fmt);
00353       fprintf(qlog, "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
00354       vfprintf(qlog, fmt, ap);
00355       fprintf(qlog, "\n");
00356       va_end(ap);
00357       fflush(qlog);
00358    }
00359    AST_LIST_UNLOCK(&logchannels);
00360 }
00361 
00362 int reload_logger(int rotate)
00363 {
00364    char old[PATH_MAX] = "";
00365    char new[PATH_MAX];
00366    int event_rotate = rotate, queue_rotate = rotate;
00367    struct logchannel *f;
00368    FILE *myf;
00369    int x, res = 0;
00370 
00371    AST_LIST_LOCK(&logchannels);
00372 
00373    if (eventlog) 
00374       fclose(eventlog);
00375    else 
00376       event_rotate = 0;
00377    eventlog = NULL;
00378 
00379    if (qlog) 
00380       fclose(qlog);
00381    else 
00382       queue_rotate = 0;
00383    qlog = NULL;
00384 
00385    mkdir((char *)ast_config_AST_LOG_DIR, 0755);
00386 
00387    AST_LIST_TRAVERSE(&logchannels, f, list) {
00388       if (f->disabled) {
00389          f->disabled = 0;  /* Re-enable logging at reload */
00390          manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
00391       }
00392       if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
00393          fclose(f->fileptr);  /* Close file */
00394          f->fileptr = NULL;
00395          if (rotate) {
00396             ast_copy_string(old, f->filename, sizeof(old));
00397    
00398             for (x = 0; ; x++) {
00399                snprintf(new, sizeof(new), "%s.%d", f->filename, x);
00400                myf = fopen((char *)new, "r");
00401                if (myf)
00402                   fclose(myf);
00403                else
00404                   break;
00405             }
00406        
00407             /* do it */
00408             if (rename(old,new))
00409                fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
00410          }
00411       }
00412    }
00413 
00414    filesize_reload_needed = 0;
00415    
00416    init_logger_chain();
00417 
00418    if (logfiles.event_log) {
00419       snprintf(old, sizeof(old), "%s/%s", (char *)ast_config_AST_LOG_DIR, EVENTLOG);
00420       if (event_rotate) {
00421          for (x=0;;x++) {
00422             snprintf(new, sizeof(new), "%s/%s.%d", (char *)ast_config_AST_LOG_DIR, EVENTLOG,x);
00423             myf = fopen((char *)new, "r");
00424             if (myf)    /* File exists */
00425                fclose(myf);
00426             else
00427                break;
00428          }
00429    
00430          /* do it */
00431          if (rename(old,new))
00432             ast_log(LOG_ERROR, "Unable to rename file '%s' to '%s'\n", old, new);
00433       }
00434 
00435       eventlog = fopen(old, "a");
00436       if (eventlog) {
00437          ast_log(LOG_EVENT, "Restarted Asterisk Event Logger\n");
00438          if (option_verbose)
00439             ast_verbose("Asterisk Event Logger restarted\n");
00440       } else {
00441          ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
00442          res = -1;
00443       }
00444    }
00445 
00446    if (logfiles.queue_log) {
00447       snprintf(old, sizeof(old), "%s/%s", (char *)ast_config_AST_LOG_DIR, QUEUELOG);
00448       if (queue_rotate) {
00449          for (x = 0; ; x++) {
00450             snprintf(new, sizeof(new), "%s/%s.%d", (char *)ast_config_AST_LOG_DIR, QUEUELOG, x);
00451             myf = fopen((char *)new, "r");
00452             if (myf)    /* File exists */
00453                fclose(myf);
00454             else
00455                break;
00456          }
00457    
00458          /* do it */
00459          if (rename(old, new))
00460             ast_log(LOG_ERROR, "Unable to rename file '%s' to '%s'\n", old, new);
00461       }
00462 
00463       qlog = fopen(old, "a");
00464       if (qlog) {
00465          ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
00466          ast_log(LOG_EVENT, "Restarted Asterisk Queue Logger\n");
00467          if (option_verbose)
00468             ast_verbose("Asterisk Queue Logger restarted\n");
00469       } else {
00470          ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
00471          res = -1;
00472       }
00473    }
00474 
00475    AST_LIST_UNLOCK(&logchannels);
00476 
00477    return res;
00478 }
00479 
00480 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
00481    a full Asterisk reload) */
00482 int logger_reload(void)
00483 {
00484    if(reload_logger(0))
00485       return RESULT_FAILURE;
00486    return RESULT_SUCCESS;
00487 }
00488 
00489 static int handle_logger_reload(int fd, int argc, char *argv[])
00490 {
00491    int result = logger_reload();
00492    if (result == RESULT_FAILURE)
00493       ast_cli(fd, "Failed to reload the logger\n");
00494    return result;
00495 }
00496 
00497 static int handle_logger_rotate(int fd, int argc, char *argv[])
00498 {
00499    if(reload_logger(1)) {
00500       ast_cli(fd, "Failed to reload the logger and rotate log files\n");
00501       return RESULT_FAILURE;
00502    }
00503    return RESULT_SUCCESS;
00504 }
00505 
00506 /*! \brief CLI command to show logging system configuration */
00507 static int handle_logger_show_channels(int fd, int argc, char *argv[])
00508 {
00509 #define FORMATL   "%-35.35s %-8.8s %-9.9s "
00510    struct logchannel *chan;
00511 
00512    ast_cli(fd,FORMATL, "Channel", "Type", "Status");
00513    ast_cli(fd, "Configuration\n");
00514    ast_cli(fd,FORMATL, "-------", "----", "------");
00515    ast_cli(fd, "-------------\n");
00516    AST_LIST_LOCK(&logchannels);
00517    AST_LIST_TRAVERSE(&logchannels, chan, list) {
00518       ast_cli(fd, FORMATL, chan->filename, chan->type==LOGTYPE_CONSOLE ? "Console" : (chan->type==LOGTYPE_SYSLOG ? "Syslog" : "File"),
00519          chan->disabled ? "Disabled" : "Enabled");
00520       ast_cli(fd, " - ");
00521       if (chan->logmask & (1 << __LOG_DEBUG)) 
00522          ast_cli(fd, "Debug ");
00523       if (chan->logmask & (1 << __LOG_DTMF)) 
00524          ast_cli(fd, "DTMF ");
00525       if (chan->logmask & (1 << __LOG_VERBOSE)) 
00526          ast_cli(fd, "Verbose ");
00527       if (chan->logmask & (1 << __LOG_WARNING)) 
00528          ast_cli(fd, "Warning ");
00529       if (chan->logmask & (1 << __LOG_NOTICE)) 
00530          ast_cli(fd, "Notice ");
00531       if (chan->logmask & (1 << __LOG_ERROR)) 
00532          ast_cli(fd, "Error ");
00533       if (chan->logmask & (1 << __LOG_EVENT)) 
00534          ast_cli(fd, "Event ");
00535       ast_cli(fd, "\n");
00536    }
00537    AST_LIST_UNLOCK(&logchannels);
00538    ast_cli(fd, "\n");
00539       
00540    return RESULT_SUCCESS;
00541 }
00542 
00543 struct verb {
00544    void (*verboser)(const char *string);
00545    AST_LIST_ENTRY(verb) list;
00546 };
00547 
00548 static AST_LIST_HEAD_STATIC(verbosers, verb);
00549 
00550 static char logger_reload_help[] =
00551 "Usage: logger reload\n"
00552 "       Reloads the logger subsystem state.  Use after restarting syslogd(8) if you are using syslog logging.\n";
00553 
00554 static char logger_rotate_help[] =
00555 "Usage: logger rotate\n"
00556 "       Rotates and Reopens the log files.\n";
00557 
00558 static char logger_show_channels_help[] =
00559 "Usage: logger show channels\n"
00560 "       List configured logger channels.\n";
00561 
00562 static struct ast_cli_entry cli_logger[] = {
00563    { { "logger", "show", "channels", NULL }, 
00564    handle_logger_show_channels, "List configured log channels",
00565    logger_show_channels_help },
00566 
00567    { { "logger", "reload", NULL }, 
00568    handle_logger_reload, "Reopens the log files",
00569    logger_reload_help },
00570 
00571    { { "logger", "rotate", NULL }, 
00572    handle_logger_rotate, "Rotates and reopens the log files",
00573    logger_rotate_help },
00574 };
00575 
00576 static int handle_SIGXFSZ(int sig) 
00577 {
00578    /* Indicate need to reload */
00579    filesize_reload_needed = 1;
00580    return 0;
00581 }
00582 
00583 int init_logger(void)
00584 {
00585    char tmp[256];
00586    int res = 0;
00587 
00588    /* auto rotate if sig SIGXFSZ comes a-knockin */
00589    (void) signal(SIGXFSZ,(void *) handle_SIGXFSZ);
00590 
00591    /* register the logger cli commands */
00592    ast_cli_register_multiple(cli_logger, sizeof(cli_logger) / sizeof(struct ast_cli_entry));
00593 
00594    mkdir((char *)ast_config_AST_LOG_DIR, 0755);
00595   
00596    /* create log channels */
00597    init_logger_chain();
00598 
00599    /* create the eventlog */
00600    if (logfiles.event_log) {
00601       mkdir((char *)ast_config_AST_LOG_DIR, 0755);
00602       snprintf(tmp, sizeof(tmp), "%s/%s", (char *)ast_config_AST_LOG_DIR, EVENTLOG);
00603       eventlog = fopen((char *)tmp, "a");
00604       if (eventlog) {
00605          ast_log(LOG_EVENT, "Started Asterisk Event Logger\n");
00606          if (option_verbose)
00607             ast_verbose("Asterisk Event Logger Started %s\n",(char *)tmp);
00608       } else {
00609          ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
00610          res = -1;
00611       }
00612    }
00613 
00614    if (logfiles.queue_log) {
00615       snprintf(tmp, sizeof(tmp), "%s/%s", (char *)ast_config_AST_LOG_DIR, QUEUELOG);
00616       qlog = fopen(tmp, "a");
00617       ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
00618    }
00619    return res;
00620 }
00621 
00622 void close_logger(void)
00623 {
00624    struct logchannel *f;
00625 
00626    AST_LIST_LOCK(&logchannels);
00627 
00628    if (eventlog) {
00629       fclose(eventlog);
00630       eventlog = NULL;
00631    }
00632 
00633    if (qlog) {
00634       fclose(qlog);
00635       qlog = NULL;
00636    }
00637 
00638    AST_LIST_TRAVERSE(&logchannels, f, list) {
00639       if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
00640          fclose(f->fileptr);
00641          f->fileptr = NULL;
00642       }
00643    }
00644 
00645    closelog(); /* syslog */
00646 
00647    AST_LIST_UNLOCK(&logchannels);
00648 
00649    return;
00650 }
00651 
00652 static void __attribute__((format(printf, 5, 0))) ast_log_vsyslog(int level, const char *file, int line, const char *function, const char *fmt, va_list args) 
00653 {
00654    char buf[BUFSIZ];
00655    char *s;
00656 
00657    if (level >= SYSLOG_NLEVELS) {
00658       /* we are locked here, so cannot ast_log() */
00659       fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
00660       return;
00661    }
00662    if (level == __LOG_VERBOSE) {
00663       snprintf(buf, sizeof(buf), "VERBOSE[%ld]: ", (long)GETTID());
00664       level = __LOG_DEBUG;
00665    } else if (level == __LOG_DTMF) {
00666       snprintf(buf, sizeof(buf), "DTMF[%ld]: ", (long)GETTID());
00667       level = __LOG_DEBUG;
00668    } else {
00669       snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: ",
00670           levels[level], (long)GETTID(), file, line, function);
00671    }
00672    s = buf + strlen(buf);
00673    vsnprintf(s, sizeof(buf) - strlen(buf), fmt, args);
00674    term_strip(s, s, strlen(s) + 1);
00675    syslog(syslog_level_map[level], "%s", buf);
00676 }
00677 
00678 /*!
00679  * \brief send log messages to syslog and/or the console
00680  */
00681 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
00682 {
00683    struct logchannel *chan;
00684    struct ast_dynamic_str *buf;
00685    time_t t;
00686    struct tm tm;
00687    char date[256];
00688 
00689    va_list ap;
00690 
00691    if (!(buf = ast_dynamic_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
00692       return;
00693 
00694    if (AST_LIST_EMPTY(&logchannels))
00695    {
00696       /*
00697        * we don't have the logger chain configured yet,
00698        * so just log to stdout
00699       */
00700       if (level != __LOG_VERBOSE) {
00701          int res;
00702          va_start(ap, fmt);
00703          res = ast_dynamic_str_thread_set_va(&buf, BUFSIZ, &log_buf, fmt, ap);
00704          va_end(ap);
00705          if (res != AST_DYNSTR_BUILD_FAILED) {
00706             term_filter_escapes(buf->str);
00707             fputs(buf->str, stdout);
00708          }
00709       }
00710       return;
00711    }
00712 
00713    /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
00714       are non-zero; LOG_DEBUG messages can still be displayed if option_debug
00715       is zero, if option_verbose is non-zero (this allows for 'level zero'
00716       LOG_DEBUG messages to be displayed, if the logmask on any channel
00717       allows it)
00718    */
00719    if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
00720       return;
00721 
00722    /* Ignore anything that never gets logged anywhere */
00723    if (!(global_logmask & (1 << level)))
00724       return;
00725    
00726    /* Ignore anything other than the currently debugged file if there is one */
00727    if ((level == __LOG_DEBUG) && !ast_strlen_zero(debug_filename) && strcasecmp(debug_filename, file))
00728       return;
00729 
00730    time(&t);
00731    ast_localtime(&t, &tm, NULL);
00732    strftime(date, sizeof(date), dateformat, &tm);
00733 
00734    AST_LIST_LOCK(&logchannels);
00735 
00736    if (logfiles.event_log && level == __LOG_EVENT) {
00737       va_start(ap, fmt);
00738 
00739       fprintf(eventlog, "%s asterisk[%ld]: ", date, (long)getpid());
00740       vfprintf(eventlog, fmt, ap);
00741       fflush(eventlog);
00742 
00743       va_end(ap);
00744       AST_LIST_UNLOCK(&logchannels);
00745       return;
00746    }
00747 
00748    AST_LIST_TRAVERSE(&logchannels, chan, list) {
00749       if (chan->disabled)
00750          break;
00751       /* Check syslog channels */
00752       if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << level))) {
00753          va_start(ap, fmt);
00754          ast_log_vsyslog(level, file, line, function, fmt, ap);
00755          va_end(ap);
00756       /* Console channels */
00757       } else if ((chan->logmask & (1 << level)) && (chan->type == LOGTYPE_CONSOLE)) {
00758          char linestr[128];
00759          char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
00760 
00761          if (level != __LOG_VERBOSE) {
00762             int res;
00763             sprintf(linestr, "%d", line);
00764             ast_dynamic_str_thread_set(&buf, BUFSIZ, &log_buf,
00765                "[%s] %s[%ld]: %s:%s %s: ",
00766                date,
00767                term_color(tmp1, levels[level], colors[level], 0, sizeof(tmp1)),
00768                (long)GETTID(),
00769                term_color(tmp2, file, COLOR_BRWHITE, 0, sizeof(tmp2)),
00770                term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
00771                term_color(tmp4, function, COLOR_BRWHITE, 0, sizeof(tmp4)));
00772             /*filter to the console!*/
00773             term_filter_escapes(buf->str);
00774             ast_console_puts_mutable(buf->str);
00775             
00776             va_start(ap, fmt);
00777             res = ast_dynamic_str_thread_set_va(&buf, BUFSIZ, &log_buf, fmt, ap);
00778             va_end(ap);
00779             if (res != AST_DYNSTR_BUILD_FAILED)
00780                ast_console_puts_mutable(buf->str);
00781          }
00782       /* File channels */
00783       } else if ((chan->logmask & (1 << level)) && (chan->fileptr)) {
00784          int res;
00785          ast_dynamic_str_thread_set(&buf, BUFSIZ, &log_buf, 
00786             "[%s] %s[%ld] %s: ",
00787             date, levels[level], (long)GETTID(), file);
00788          res = fprintf(chan->fileptr, "%s", buf->str);
00789          if (res <= 0 && !ast_strlen_zero(buf->str)) {   /* Error, no characters printed */
00790             fprintf(stderr,"**** Asterisk Logging Error: ***********\n");
00791             if (errno == ENOMEM || errno == ENOSPC) {
00792                fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
00793             } else
00794                fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
00795             manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
00796             chan->disabled = 1;  
00797          } else {
00798             int res;
00799             /* No error message, continue printing */
00800             va_start(ap, fmt);
00801             res = ast_dynamic_str_thread_set_va(&buf, BUFSIZ, &log_buf, fmt, ap);
00802             va_end(ap);
00803             if (res != AST_DYNSTR_BUILD_FAILED) {
00804                term_strip(buf->str, buf->str, buf->len);
00805                fputs(buf->str, chan->fileptr);
00806                fflush(chan->fileptr);
00807             }
00808          }
00809       }
00810    }
00811 
00812    AST_LIST_UNLOCK(&logchannels);
00813 
00814    if (filesize_reload_needed) {
00815       reload_logger(1);
00816       ast_log(LOG_EVENT,"Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
00817       if (option_verbose)
00818          ast_verbose("Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
00819    }
00820 }
00821 
00822 void ast_backtrace(void)
00823 {
00824 #ifdef linux
00825 #ifdef AST_DEVMODE
00826    int count=0, i=0;
00827    void **addresses;
00828    char **strings;
00829 
00830    if ((addresses = ast_calloc(MAX_BACKTRACE_FRAMES, sizeof(*addresses)))) {
00831       count = backtrace(addresses, MAX_BACKTRACE_FRAMES);
00832       if ((strings = backtrace_symbols(addresses, count))) {
00833          ast_log(LOG_DEBUG, "Got %d backtrace record%c\n", count, count != 1 ? 's' : ' ');
00834          for (i=0; i < count ; i++) {
00835 #if __WORDSIZE == 32
00836             ast_log(LOG_DEBUG, "#%d: [%08X] %s\n", i, (unsigned int)addresses[i], strings[i]);
00837 #elif __WORDSIZE == 64
00838             ast_log(LOG_DEBUG, "#%d: [%016lX] %s\n", i, (unsigned long)addresses[i], strings[i]);
00839 #endif
00840          }
00841          free(strings);
00842       } else {
00843          ast_log(LOG_DEBUG, "Could not allocate memory for backtrace\n");
00844       }
00845       free(addresses);
00846    }
00847 #else
00848    ast_log(LOG_WARNING, "Must run configure with '--enable-dev-mode' for stack backtraces.\n");
00849 #endif
00850 #else /* ndef linux */
00851    ast_log(LOG_WARNING, "Inline stack backtraces are only available on the Linux platform.\n");
00852 #endif
00853 }
00854 
00855 void ast_verbose(const char *fmt, ...)
00856 {
00857    struct verb *v;
00858    struct ast_dynamic_str *buf;
00859    int res;
00860    va_list ap;
00861 
00862    if (ast_opt_timestamp) {
00863       time_t t;
00864       struct tm tm;
00865       char date[40];
00866       char *datefmt;
00867 
00868       time(&t);
00869       ast_localtime(&t, &tm, NULL);
00870       strftime(date, sizeof(date), dateformat, &tm);
00871       datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
00872       sprintf(datefmt, "%c[%s] %s", 127, date, fmt);
00873       fmt = datefmt;
00874    } else {
00875       char *tmp = alloca(strlen(fmt) + 2);
00876       sprintf(tmp, "%c%s", 127, fmt);
00877       fmt = tmp;
00878    }
00879 
00880    if (!(buf = ast_dynamic_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
00881       return;
00882 
00883    va_start(ap, fmt);
00884    res = ast_dynamic_str_thread_set_va(&buf, 0, &verbose_buf, fmt, ap);
00885    va_end(ap);
00886 
00887    if (res == AST_DYNSTR_BUILD_FAILED)
00888       return;
00889    
00890    /* filter out possibly hazardous escape sequences */
00891    term_filter_escapes(buf->str);
00892 
00893    AST_LIST_LOCK(&verbosers);
00894    AST_LIST_TRAVERSE(&verbosers, v, list)
00895       v->verboser(buf->str);
00896    AST_LIST_UNLOCK(&verbosers);
00897 
00898    ast_log(LOG_VERBOSE, "%s", buf->str + 1);
00899 }
00900 
00901 int ast_register_verbose(void (*v)(const char *string)) 
00902 {
00903    struct verb *verb;
00904 
00905    if (!(verb = ast_malloc(sizeof(*verb))))
00906       return -1;
00907 
00908    verb->verboser = v;
00909 
00910    AST_LIST_LOCK(&verbosers);
00911    AST_LIST_INSERT_HEAD(&verbosers, verb, list);
00912    AST_LIST_UNLOCK(&verbosers);
00913    
00914    return 0;
00915 }
00916 
00917 int ast_unregister_verbose(void (*v)(const char *string))
00918 {
00919    struct verb *cur;
00920 
00921    AST_LIST_LOCK(&verbosers);
00922    AST_LIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
00923       if (cur->verboser == v) {
00924          AST_LIST_REMOVE_CURRENT(&verbosers, list);
00925          free(cur);
00926          break;
00927       }
00928    }
00929    AST_LIST_TRAVERSE_SAFE_END
00930    AST_LIST_UNLOCK(&verbosers);
00931    
00932    return cur ? 0 : -1;
00933 }

Generated on Fri Jan 29 14:25:16 2010 for Asterisk - the Open Source PBX by  doxygen 1.4.7