101 lines
1.8 KiB
C
101 lines
1.8 KiB
C
//
|
|
// Logging
|
|
//
|
|
|
|
#include "netlib.h"
|
|
#include "strlib.h"
|
|
|
|
#include <stdarg.h>
|
|
#include <sys/param.h>
|
|
#include <sys/stat.h>
|
|
#include <sys/types.h>
|
|
#include <time.h>
|
|
#include <sys/time.h>
|
|
|
|
static char szLogPath[MAXPATHLEN-5] = "/var/log/" VAR_LOG_RUN_NAME "/";
|
|
static char szLogFile[MAXPATHLEN-5];
|
|
static FILE *pLog = NULL;
|
|
static char bLogFlag = 1;
|
|
|
|
void log_on(void)
|
|
{
|
|
bLogFlag = 1;
|
|
}
|
|
|
|
void log_off(void)
|
|
{
|
|
bLogFlag = 0;
|
|
}
|
|
|
|
void log_exit( void )
|
|
{
|
|
if ( pLog )
|
|
{
|
|
log_printf( "Closed logfile (euid = %d.%d)", geteuid(), getegid() );
|
|
fclose( pLog );
|
|
}
|
|
}
|
|
|
|
void log_path( const char *pszPath )
|
|
{
|
|
strlcpy( szLogPath, pszPath, sizeof(szLogPath) );
|
|
}
|
|
|
|
FILE *log_open( const char *pszFile )
|
|
{
|
|
mkdir(szLogPath, 0776);
|
|
snprintf(szLogFile, MAXPATHLEN-1, "%s%s.log", szLogPath, pszFile);
|
|
|
|
if ( (pLog = fopen( szLogFile, "a" )) )
|
|
{
|
|
log_printf( "Opened logfile: %s (uid = %d.%d)", szLogFile, getuid(), getgid() );
|
|
atexit( log_exit );
|
|
}
|
|
else
|
|
{
|
|
perror( szLogFile );
|
|
}
|
|
return pLog;
|
|
}
|
|
|
|
void log_write( const char *msg )
|
|
{
|
|
if ( !pLog || !bLogFlag || !msg || !strlen(msg) )
|
|
return;
|
|
|
|
/* time stamp it */
|
|
time_t t = time(NULL);
|
|
struct tm *tm = localtime( &t );
|
|
char szBuf[30];
|
|
strftime( szBuf, sizeof(szBuf), "%F %T ", tm );
|
|
|
|
fprintf( pLog, "%s %s\n", szBuf, msg );
|
|
fflush( pLog );
|
|
}
|
|
|
|
void log_printf( const char *fmt, ... )
|
|
{
|
|
va_list ap;
|
|
if ( !pLog || !bLogFlag || !fmt )
|
|
return;
|
|
|
|
/* time stamp it */
|
|
time_t t = time(NULL);
|
|
struct tm *tm = localtime( &t );
|
|
char szBuf[30];
|
|
strftime( szBuf, sizeof(szBuf), "%F %T ", tm );
|
|
fprintf( pLog, "%s", szBuf );
|
|
|
|
va_start( ap, fmt );
|
|
vfprintf( pLog, fmt, ap );
|
|
va_end( ap );
|
|
fputs( "\n", pLog );
|
|
fflush( pLog );
|
|
}
|
|
|
|
void log_error( const char *msg )
|
|
{
|
|
perror(msg);
|
|
log_printf( "%s (%s)", msg, strerror(errno) );
|
|
}
|