LogIt++
Header-only, macro-first C++ logging library
Loading...
Searching...
No Matches
system_error_macros.hpp
Go to the documentation of this file.
1#pragma once
2#ifndef LOGIT_CPP_HEADER_LOGIT_CPP_LOGIT_DETAIL_SYSTEM_ERROR_MACROS_HPP_INCLUDED
3#define LOGIT_CPP_HEADER_LOGIT_CPP_LOGIT_DETAIL_SYSTEM_ERROR_MACROS_HPP_INCLUDED
4
5#include <errno.h>
6#include <cstring>
7#include <string>
8
11
12#if defined(_WIN32)
13#include <windows.h>
14#endif
15
16namespace logit {
17namespace detail {
18
19#if defined(_WIN32)
20inline std::string _logit_format_winerr(DWORD code) {
21 LPSTR buffer = nullptr;
22 const DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
23 const DWORD length = ::FormatMessageA(flags,
24 nullptr,
25 code,
26 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
27 reinterpret_cast<LPSTR>(&buffer),
28 0,
29 nullptr);
30
31 if (length == 0 || buffer == nullptr) {
32 return std::string();
33 }
34
35 std::string message(buffer, length);
36 ::LocalFree(buffer);
37
38 while (!message.empty() && (message.back() == '\r' || message.back() == '\n')) {
39 message.pop_back();
40 }
41
42 return message;
43}
44#endif // defined(_WIN32)
45
46} // namespace detail
47} // namespace logit
48
49#define LOGIT_DETAIL_PERROR(level_macro, message) \
50 do { \
51 const int _logit_errno_code = (errno); \
52 const char *_logit_errno_desc = ::strerror(_logit_errno_code); \
53 if (_logit_errno_desc == nullptr) { \
54 _logit_errno_desc = ""; \
55 } \
56 const std::string _logit_errno_text(message); \
57 LOGIT_PRINTF_##level_macro(LOGIT_POSIX_ERROR_PATTERN, \
58 _logit_errno_text.c_str(), \
59 _logit_errno_code, \
60 _logit_errno_desc); \
61 } while (0)
62
63#if defined(_WIN32)
64
65#define LOGIT_DETAIL_WINERR(level_macro, message) \
66 do { \
67 const DWORD _logit_winerr_code = ::GetLastError(); \
68 const std::string _logit_winerr_text(message); \
69 const std::string _logit_winerr_desc = ::logit::detail::_logit_format_winerr(_logit_winerr_code); \
70 LOGIT_PRINTF_##level_macro(LOGIT_WINDOWS_ERROR_PATTERN, \
71 _logit_winerr_text.c_str(), \
72 static_cast<unsigned long>(_logit_winerr_code), \
73 _logit_winerr_desc.c_str()); \
74 } while (0)
75
76#else // defined(_WIN32)
77
78#define LOGIT_DETAIL_WINERR(level_macro, message) do { } while (0)
79
80#endif // defined(_WIN32)
81
82#endif // LOGIT_CPP_HEADER_LOGIT_CPP_LOGIT_DETAIL_SYSTEM_ERROR_MACROS_HPP_INCLUDED
The primary namespace for the LogIt++ library.