bux API Reference 1.9.0
Static library of whatever are seen required in general purpose but not directly supported from Modern C++. Or whatever reusable originated from my side projects.
Loading...
Searching...
No Matches
LogStream.cpp
Go to the documentation of this file.
1#include "LogStream.h"
2//---------------------------------------------------------------
3#include <ostream> // std::ostream
4#include <cinttypes> // imaxdiv()
5#include <cstring> // std::strcpy()
6
7#define STD_FORMAT_CHRONO_
8#ifndef STD_FORMAT_CHRONO_
9#include <ctime> // std::localtime(), std::strftime()
10#endif
11
12#ifdef __GNUC__
13#ifndef _GNU_SOURCE
14#define _GNU_SOURCE // or _BSD_SOURCE or _SVID_SOURCE
15#endif
16#include <unistd.h>
17#include <sys/syscall.h> // for SYS_xxx definitions
18
19#define TID_ syscall(SYS_gettid)
20#elif defined(_WIN32)
21#include <windows.h> // GetCurrentThreadId()
22
23#define TID_ GetCurrentThreadId()
24#else
25#include <thread> // std::this_thread::get_id()
26
27#define TID_ std::this_thread::get_id()
28#endif
29
30namespace bux {
31
32std::ostream &timestamp(std::ostream &out, const std::chrono::time_zone *tz)
39{
40 typedef std::chrono::system_clock myclock;
41 static char YMDHMS[30];
42 static std::chrono::time_point<myclock,std::chrono::milliseconds> old_time;
43 static const std::chrono::time_zone *old_tz = nullptr;
44 const auto cur_time = time_point_cast<std::chrono::milliseconds>(myclock::now());
45 if (cur_time != old_time || tz != old_tz)
46 {
47#ifdef STD_FORMAT_CHRONO_
48 constexpr const std::string_view TIMESTAMP_FMT = "{:%Y/%m/%d %H:%M:%S}";
49 auto tm_str = tz? std::format(TIMESTAMP_FMT, tz->to_local(cur_time)): std::format(TIMESTAMP_FMT, cur_time);
50 std::strcpy(YMDHMS, tm_str.c_str());
51#else
52 auto d = imaxdiv(cur_time.time_since_epoch().count(), 1000);
53 time_t t = d.quot;
54 std::sprintf(YMDHMS + std::strftime(YMDHMS, sizeof YMDHMS, "%Y/%m/%d %H:%M:%S", std::localtime(&t)), ".%03" PRIdMAX, d.rem);
55#endif
56 old_time = cur_time;
57 old_tz = tz;
58 }
59 return out <<YMDHMS;
60}
61
62std::ostream &logTrace(std::ostream &out, const std::chrono::time_zone *tz)
69{
70 return timestamp(out,tz) <<" tid" <<TID_ <<' ';
71}
72
73} // namespace bux
#define TID_
Definition LogStream.cpp:19
THE common namespace of bux library.
Definition AtomiX.cpp:3
std::ostream & timestamp(std::ostream &out, const std::chrono::time_zone *tz)
Definition LogStream.cpp:32
std::ostream & logTrace(std::ostream &out, const std::chrono::time_zone *tz)
Definition LogStream.cpp:62