-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLoggerModule.hpp
More file actions
62 lines (49 loc) · 2.36 KB
/
LoggerModule.hpp
File metadata and controls
62 lines (49 loc) · 2.36 KB
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
#include <iomanip>
#include <sstream>
#include "ziapi/Logger.hpp"
#include "ziapi/Module.hpp"
class LoggerModule : virtual public ziapi::IPreProcessorModule, public ziapi::IPostProcessorModule {
public:
void Init(const ziapi::config::Node &config) {}
[[nodiscard]] ziapi::Version GetVersion() const noexcept override { return {4, 0, 0}; }
[[nodiscard]] ziapi::Version GetCompatibleApiVersion() const noexcept override { return {4, 0, 0}; }
[[nodiscard]] const char *GetName() const noexcept override { return "LoggerModule"; }
[[nodiscard]] const char *GetDescription() const noexcept override
{
return "Log all responses from HTTP requests";
}
[[nodiscard]] double GetPostProcessorPriority() const noexcept override { return 1; }
[[nodiscard]] bool ShouldPostProcess(const ziapi::http::Context &ctx, const ziapi::http::Request &req,
const ziapi::http::Response &res) const override
{
return true;
}
[[nodiscard]] double GetPreProcessorPriority() const noexcept override { return 0; }
[[nodiscard]] bool ShouldPreProcess(const ziapi::http::Context &ctx, const ziapi::http::Request &req) const override
{
return true;
}
void PostProcess(ziapi::http::Context &ctx, const ziapi::http::Request &, ziapi::http::Response &res) override
{
std::stringstream ss;
// Exemple: ` [X] 404: Not found (GET /test, 2s)`
ss << std::to_string((int)res.status_code) << ": " << res.reason << " ("
<< std::any_cast<std::string>(ctx["method"]) << " " << std::any_cast<std::string>(ctx["target"]) << ", "
<< std::setprecision(2) << difftime(std::time(nullptr), std::any_cast<time_t>(ctx["timestamp"])) << "s)";
if ((int)res.status_code < 300) {
ziapi::Logger::Info(ss.str());
} else if ((int)res.status_code < 400) {
ziapi::Logger::Warning(ss.str());
} else {
ziapi::Logger::Error(ss.str());
}
}
void PreProcess(ziapi::http::Context &ctx, ziapi::http::Request &req) override
{
ctx["timestamp"] = std::time(nullptr);
/// This example is deprecrated. Storing the target and method is useless because the `PostProcess` method now
/// has access to the request object.
ctx["target"] = req.target;
ctx["method"] = req.method;
}
};