libsclogging/logger.cpp

47 lines
1.2 KiB
C++
Raw Normal View History

//
// logger.cpp
// libsclogging
//
// Created by Bob Polis at 2020-04-29
// Copyright (c) 2020 SwiftCoder. All rights reserved.
//
#include "logger.hpp"
2020-04-29 16:54:58 +02:00
#include <unistd.h>
2020-04-29 17:41:23 +02:00
#include <sys/time.h>
#include <ctime>
#include <cmath>
#include <iomanip>
using namespace sc;
2020-04-29 16:54:58 +02:00
logger::logger(const std::string& name, loglevel level)
: _level(level), _name(name) {}
void logger::msg(loglevel level, const char* file, int line, const char* func) {
if (level >= _level) {
if (_topcall) {
write_prefix(level, file, line, func);
} else {
_topcall = true;
}
std::cerr << '\n';
}
}
void logger::write_prefix(loglevel level, const char* file, int line, const char* func) {
2020-04-29 17:41:23 +02:00
// retrieve accurate time for milliseconds display
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-04-29 16:54:58 +02:00
std::cerr << _name << "[" << ::getpid() << "] ";
std::cerr << file << ":" << line << " " << func << "() ";
std::cerr << '[' << loglevel_desc(level) << "] ";
}