map/das-dn/third_party/AdsLib/Log.cpp
2024-12-03 10:36:06 +08:00

57 lines
1.8 KiB
C++

// SPDX-License-Identifier: MIT
/**
Copyright (c) 2015 -2022 Beckhoff Automation GmbH & Co. KG
Author: Patrick Bruenn <p.bruenn@beckhoff.com>
*/
#include "Log.h"
#include <algorithm>
#include <chrono>
#include <ctime>
#include <fstream>
#include <iostream>
#include "public.h"
#ifdef _WIN32
#define TIME_T_TO_STRING(DATE_TIME, TIME_T) do { \
struct tm temp; \
localtime_s(&temp, TIME_T); \
std::strftime(DATE_TIME, sizeof(DATE_TIME), "%Y-%m-%d %H:%M:%S ", &temp); \
} while (0);
#elif defined(__CYGWIN__)
#define TIME_T_TO_STRING(DATE_TIME, TIME_T) std::strftime(DATE_TIME, sizeof(DATE_TIME), "%FT%T ", localtime(TIME_T));
#else
//#define TIME_T_TO_STRING(DATE_TIME, TIME_T) std::strftime(DATE_TIME, sizeof(DATE_TIME), "%FT%T%z ", localtime(TIME_T));
#define TIME_T_TO_STRING(DATE_TIME, TIME_T) std::strftime(DATE_TIME, sizeof(DATE_TIME), "%FT%T", localtime(TIME_T));
#endif
size_t Logger::logLevel = CONFIG_DEFAULT_LOGLEVEL;
static const char* CATEGORY[] = {
"DEBUG ",
"INFO ",
"WARN ",
"ERROR "
};
void Logger::Log(const size_t level, const std::string& msg)
{
if (level >= logLevel) {
#if 0
std::chrono::system_clock::time_point tp = std::chrono::system_clock::now();
std::time_t tt = std::chrono::system_clock::to_time_t(tp);
const auto category = CATEGORY[std::min(level, sizeof(CATEGORY) / sizeof(CATEGORY[0]))];
char dateTime[28];
//TODO use std::put_time() when available
TIME_T_TO_STRING(dateTime, &tt);
std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch()) % 1000;
//std::cerr << dateTime << category << msg << std::endl;
std::cerr << dateTime << "." << ms.count() << " [" << category << "] - " << msg << std::endl;
#endif
vLog((eLogLevel)level, "%s\n", msg.c_str());
}
}