Skip to content

Instantly share code, notes, and snippets.

@VincenzoLaSpesa
Created October 29, 2022 09:14
Show Gist options
  • Select an option

  • Save VincenzoLaSpesa/eac5a3765be02b72c5d9ef24cf8cb568 to your computer and use it in GitHub Desktop.

Select an option

Save VincenzoLaSpesa/eac5a3765be02b72c5d9ef24cf8cb568 to your computer and use it in GitHub Desktop.
A tiny headers-only logging class
#pragma once
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <mutex>
#include <chrono>
#include <ctime>
enum class LogLevel { None,
Error,
Warning,
Info,
Trace
};
class TinyLogger
{
public:
TinyLogger(const char* filename, const LogLevel &ll)
{
_basetimestamp = GetTickCount64();
_fileStream.open(filename, std::ofstream::out | std::ofstream::app);
if (_fileStream.bad())
throw std::ifstream::failure("Exception opening / reading file");
_fileStream << std::setprecision(3);
LogText("TinyLogger::TinyLogger", std::to_string(seconds_since_midnight()), true);
};
~TinyLogger()
{
_fileStream.close();
}
void LogText(const char* header, const char* message, bool printTimestamp = false)
{
std::unique_lock<std::mutex> lock(_mutex);
if (header && strlen(header) > 0)
_fileStream << header << '\t';
if (message && strlen(message) > 0)
_fileStream << message << '\t';
if (printTimestamp)
_fileStream << (float)(GetTickCount64() - _basetimestamp) / 1000.0f;
_fileStream << std::endl;
}
void LogText(const char* header, const std::string message, bool printTimestamp = false)
{
LogText(header, message.c_str(), printTimestamp);
}
void Flush()
{
std::unique_lock<std::mutex> lock(_mutex);
_fileStream.flush();
};
private:
static float seconds_since_midnight()
{
const auto now = std::chrono::system_clock::now();
const time_t tnow = std::chrono::system_clock::to_time_t(now);
tm* date = std::localtime(&tnow);
date->tm_hour = 0;
date->tm_min = 0;
date->tm_sec = 0;
const auto midnight = std::chrono::system_clock::from_time_t(std::mktime(date));
const auto delta = now - midnight;
const int ms = (int)std::chrono::duration_cast<std::chrono::milliseconds>(delta).count();
return ms / 1000.0f;
}
std::ofstream _fileStream;
uint64_t _basetimestamp;
std::mutex _mutex;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment