/* eurephia_log.c -- eurephia logging * * GPLv2 only - Copyright (C) 2008 * David Sommerseth * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ /** * @file eurephia_log.c * @author David Sommerseth * @date 2008-08-06 * * @brief Function for unified logging * */ #include #include #include #include #include #include #include "eurephia_log.h" /** * Mapping table for mapping log types (defined in eurephia_log.h) * to string values */ const char *erp_logtypes[] = { "\0", "-- INFO -- \0", /**< LOG_INFO */ "-- DEBUG -- \0", /**< LOG_DEBUG */ "** WARNING ** \0", /**< LOG_WARNING */ "** ERROR ** \0", /**< LOG_ERROR */ "** CRITICAL ** \0", /**< LOG_CRITICAL */ "** - FATAL - ** \0", /**< LOG_FATAL */ "** * PANIC * ** \0" /**< LOG_PANIC */ }; /** * POSIX Mutex to avoid simultaneously logging activity from * several threads at the same time */ pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER; /** * Simple log function which writes log data to the log file available in the eurephiaCTX * * @param ctx eurephiaCTX * @param logdst Log destination, can be LOG_INFO, LOG_DEBUG, LOG_WARNING, LOG_ERROR, * LOG_CRITICAL, LOG_FATAL or LOG_PANIC * @param loglvl Log level of the message. If the eurephiaCTX has a lower log level setup * than what this parameter is set to, the message will not be logged. * @param fmt Contents of the log message (stdarg) */ void eurephia_log(eurephiaCTX *ctx, int logdst, int loglvl, const char *fmt, ... ) { // Only log if we have an open log file and which has high enough log level if( (ctx != NULL) && (ctx->log != NULL) && (ctx->loglevel >= loglvl) ) { va_list ap; char tstmp_str[200]; time_t tstmp; struct tm *loctstmp; // Get time stamp memset(&tstmp_str, 0, 200); tstmp = time(NULL); loctstmp = localtime(&tstmp); if( loctstmp != NULL ) { if( strftime(tstmp_str, 198, "%Y-%m-%d %H:%M:%S %Z", loctstmp) == 0 ) { snprintf(tstmp_str, 198, "(error getting time stamp string)"); } } else { snprintf(tstmp_str, 198, "(error getting timestamp)"); } va_start(ap, fmt); pthread_mutex_lock(&log_mutex); // Block other threads from writing when we write fprintf(ctx->log, "[%s] %s [%i] ", tstmp_str, erp_logtypes[logdst], loglvl); vfprintf(ctx->log, fmt, ap); fprintf(ctx->log, "\n"); fflush(ctx->log); pthread_mutex_unlock(&log_mutex); // Unblock other threads va_end(ap); } }