libsclogging/log4cpp.cpp

76 lines
1.8 KiB
C++
Raw Normal View History

2020-03-16 12:17:56 +01:00
/*
* log4cpp.cpp
*
* Created by Bob Polis on 05-07-2007.
* Copyright 2007 Thalictrum. All rights reserved.
*/
#include "log4cpp.hpp"
// UNIX
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>
// C++ Standard Library
#include <cstdio>
#include <cstdarg>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <iomanip>
2020-03-16 12:17:56 +01:00
#include <iostream>
#include <sstream>
#include <vector>
#include <mutex>
using namespace std;
stringstream glog;
pthread_mutex_t log4cpp_lock = PTHREAD_MUTEX_INITIALIZER;
mutex m;
void print_timestamp()
{
// retrieve accurate time for milliseconds display
2020-03-16 12:17:56 +01:00
struct timeval secs;
(void)::gettimeofday(&secs, nullptr);
int ms = static_cast<int>(std::roundf(secs.tv_usec / 1000.0)) % 1000;
// create a date/time stamp
char dtstamp[20];
std::strftime(dtstamp, 20, "%F %T", std::localtime(&secs.tv_sec));
std::cerr << dtstamp << "." << std::setw(3) << ms << " ";
2020-03-16 12:17:56 +01:00
#if __APPLE__
std::cerr << getprogname() << "[" << getpid() << "] ";
2020-03-16 12:17:56 +01:00
#elif __linux__
std::cerr << program_invocation_name << "[" << getpid() << "] ";
2020-03-16 12:17:56 +01:00
#endif
}
void __slog(const char* func, const char* file, int line, stringstream& ss)
{
::pthread_mutex_lock(&log4cpp_lock);
print_timestamp();
string f(file);
cerr << "(" << f.substr(f.rfind('/') + 1) << ":" << line << ") " << func << "(): " << ss.str() << endl;
ss.str("");
::pthread_mutex_unlock(&log4cpp_lock);
}
void _dlog(const char* func, const char* file, int line, const char* fmt, ...) {
lock_guard<mutex> lock {m};
print_timestamp();
string f {file};
va_list args1;
va_start(args1, fmt);
va_list args2;
va_copy(args2, args1);
vector<char> buf(1 + vsnprintf(nullptr, 0, fmt, args1));
va_end(args1);
vsnprintf(buf.data(), buf.size(), fmt, args2);
va_end(args2);
cerr << "(" << f.substr(f.rfind('/') + 1) << ":" << line << ") " << func << "(): " << buf.data() << endl;
}