aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/server/common/log.hpp
blob: 63342e94dfb0f6d03a1aa8b590d3b374d5f0205b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Copyright (c) 2019 Egor Tensin <egor@tensin.name>
// This file is part of the "math-server" project.
// For details, see https://github.com/egor-tensin/math-server
// Distributed under the MIT License.

#pragma once

#include <boost/system/error_code.hpp>

#ifdef WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif

#include <exception>
#include <format>
#include <iomanip>
#include <iostream>
#include <string>
#include <string_view>
#include <thread>
#include <utility>

namespace math::server::log {
namespace details {

inline std::size_t get_tid() {
#ifdef WIN32
    return GetCurrentThreadId();
#else
    return gettid();
#endif
}

inline std::string get_timestamp() {
    const auto now = std::chrono::system_clock::now();
    return std::format("{:%F %T%z}", std::chrono::floor<std::chrono::seconds>(now));
}

inline void log(const std::string& msg) {
    std::clog << std::format("{} | {} | {}\n", get_timestamp(), get_tid(), msg);
}

} // namespace details

template <typename... Args>
inline void log(std::format_string<Args...> fmt, Args&&... args) {
    details::log(std::format(fmt, std::forward<Args>(args)...));
}

template <typename... Args>
inline void error(std::format_string<Args...> fmt, Args&&... args) {
    details::log(std::format(fmt, std::forward<Args>(args)...));
}

inline void error(const boost::system::error_code& ec) {
    log("{}", ec.message());
}

inline void error(const std::exception& e) {
    log("{}", e.what());
}

} // namespace math::server::log