/* log_print.c by vinco at 2011-09-05
* i386-Red Hat-gcc-4.1.2
* Copyright: All Reserved
*/
#include<stdio.h>
#include<string.h>
#include<time.h> // for time()
#include<stdarg.h> // for va_list, va_start, va_end
#define Log_error(args...) LOG_Print(ERROR, __FILE__, __FUNCTION__, __LINE__, args)
#define Log_warn(args...) LOG_Print(WARN, __FILE__, __FUNCTION__, __LINE__, args)
#define Log_debug(args...) LOG_Print(DEBUG, __FILE__, __FUNCTION__, __LINE__, args)
#define Log_info(args...) LOG_Print(INFO, __FILE__, __FUNCTION__, __LINE__, args)
typedef enum
{
DEBUG = 0,
INFO,
WARN,
ERROR,
EXCEP
} LOG_Type;
static const char *LOG_TypeStr[] =
{
"DEBUG - ",
"INFO - ",
"WARN - ",
"ERROR - ",
"EXCEP - "
};
void LOG_Print( LOG_Type logtype,const char* file, const char* function, unsigned int line, const char* format, ... );
int main()
{
LOG_Print(INFO, __FILE__, __FUNCTION__, __LINE__, "wrote by vinco at %d-%d-%d \n",2011,9,5);
Log_error("wrote by vinco at %d-%d-%d \n", 2011,9,5);
Log_warn("wrote by vinco at %d-%d-%d \n", 2011,9,5);
Log_debug("wrote by vinco at %d-%d-%d \n", 2011,9,5);
Log_info("wrote by vinco at %d-%d-%d \n", 2011,9,5);
return 0;
}
void LOG_Print( LOG_Type logtype,const char* file, const char* function, unsigned int line, const char* format, ... )
{
//typedef char * va_list , so param_list_pt uninitialized
va_list param_list_pt;
struct tm *tm_ptr;
time_t curtime;
time( &curtime );
//tm_ptr = gmtime( &curtime );
tm_ptr = localtime( &curtime );
/*
tm_mon The number of months since January, in the range 0 to 11.
tm_year The number of years since 1900.
*/
fprintf( stderr, "[%04d-%02d-%02d- %02d:%02d:%02d] ", 1900 + tm_ptr->tm_year, 1 + tm_ptr->tm_mon, tm_ptr->tm_mday, tm_ptr->tm_hour, tm_ptr->tm_min, tm_ptr->tm_sec );
fprintf( stderr, "%s", LOG_TypeStr[logtype] );
fprintf( stderr, "%s/", file );
fprintf( stderr, "%s()/", function );
fprintf( stderr, "line-%d ", line );
// initialize param_list_pt
va_start( param_list_pt, format );
// no need va_arg(), for formal string is already a fix part of the parameter list
vfprintf( stderr, format, param_list_pt );
fflush( stderr );
va_end( param_list_pt );
}
compile and run it
[vinco@IPPBX-Server ctest]$ make log_print
cc log_print.c -o log_print
[vinco@IPPBX-Server ctest]$ ./log_print
[2011-09-07- 19:54:32] INFO - log_print.c/main()/line-39 wrote by vinco at 2011-9-5
[2011-09-07- 19:54:32] ERROR - log_print.c/main()/line-40 wrote by vinco at 2011-9-5
[2011-09-07- 19:54:32] WARN - log_print.c/main()/line-41 wrote by vinco at 2011-9-5
[2011-09-07- 19:54:32] DEBUG - log_print.c/main()/line-42 wrote by vinco at 2011-9-5
[2011-09-07- 19:54:32] INFO - log_print.c/main()/line-43 wrote by vinco at 2011-9-5
[vinco@IPPBX-Server ctest]$