Skip to content

Commit 2a0e289

Browse files
committed
feat:add date class
1 parent 700eaf6 commit 2a0e289

12 files changed

Lines changed: 105 additions & 21 deletions

File tree

.github/workflows/test.yml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,9 @@ jobs:
2727
cmake -G "MinGW Makefiles" .. -DENABLE_SSL=OFF
2828
make
2929
cd ..
30-
wget https://raw.githubusercontent.com/chenxuan520/gh-action-shell/main/cmd_retry.ps1
31-
./cmd_retry.ps1 ./bin/test_bin.exe 2
30+
./bin/test_bin.exe
31+
# Invoke-WebRequest -Uri "https://raw.githubusercontent.com/chenxuan520/gh-action-shell/main/cmd_retry.ps1" -OutFile ".\cmd_retry.ps1" -UseBasicParsing
32+
# ./cmd_retry.ps1 ./bin/test_bin.exe 2
3233
3334
- name: Run test #需要执行的命令
3435
if: matrix.os == 'ubuntu-latest' || matrix.os == 'macos-latest'

README.en.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,8 @@ cppnet
398398
│   └── timer.hpp
399399
└── utils
400400
├── const.hpp
401+
├── date.cpp
402+
├── date.hpp
401403
├── file.cpp
402404
├── file.hpp
403405
├── host.cpp

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,8 @@ cppnet
398398
│   └── timer.hpp
399399
└── utils
400400
├── const.hpp
401+
├── date.cpp
402+
├── date.hpp
401403
├── file.cpp
402404
├── file.hpp
403405
├── host.cpp

demo/web-server/config.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
"is_background":false,
55
"is_guard":false,
66
"log_path":"./server.log",
7+
"log_level": 0,
78
"redirects":[
89
{
910
"route":"/hello",

demo/web-server/config/config.hpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ struct Config {
4646
bool is_background = false;
4747
bool is_guard = false;
4848
std::string log_path = "";
49+
int log_level = 0;
4950
std::vector<RedirectConfig> redirects;
5051
std::vector<StaticConfig> statics;
5152
SSLConfig ssl;
@@ -55,6 +56,7 @@ struct Config {
5556
is_background = json["is_background"].bool_val;
5657
is_guard = json["is_guard"].bool_val;
5758
log_path = json["log_path"].str_val;
59+
log_level = json["log_level"].int_val;
5860
for (int i = 0; i < json["redirects"].arr.size(); i++) {
5961
RedirectConfig redirect;
6062
redirect.ParseFromJson(json["redirects"][i]);

demo/web-server/main.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,10 @@ void RunWithConfig(Config &config) {
110110
std::shared_ptr<MultiLogger> logger = std::make_shared<MultiLogger>();
111111
auto std_logger = make_shared<StdLogger>();
112112
auto file_logger = make_shared<FileLogger>();
113+
114+
std_logger->set_level(Logger::Level(config.log_level));
115+
logger->set_level(Logger::Level(config.log_level));
116+
113117
file_logger->Init(config.log_path);
114118
logger->Init({std_logger, file_logger});
115119

docs/cppnet/utils/date.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# cppnet::Date
2+
## static std::string GetNow(std::string format = "%Y/%m/%d %H:%M:%S")
3+
- 参数:`std::string format`,日期时间的格式字符串。
4+
- 返回值:`std::string`类型,按照指定格式表示的当前日期和时间。
5+
- 作用:获取当前的日期和时间,并按照指定的格式转换为字符串返回。
6+
- 说明:默认格式为"%Y/%m/%d %H:%M:%S"(其中%Y表示四位年份,%m表示两位月份,%d表示两位日期,%H表示24小时制小时,%M表示分钟,%S表示秒)。

src/cppnet/http/server/http_server.cpp

Lines changed: 33 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
#include "../../utils/const.hpp"
33
#include "../../utils/file.hpp"
44
#include "filter/http_method_filter.hpp"
5+
#include "utils/date.hpp"
56
#include <functional>
67
#include <memory>
78
#include <string>
@@ -114,39 +115,42 @@ int HttpGroup::StaticDir(
114115
auto route = ctx.req().route().GetPath();
115116
auto pos = route.find(path);
116117
if (pos == std::string::npos) {
117-
logger_->Warn("[logicerr]:static dir path error " +
118-
ctx.req().route().GetPath() + " " + path);
118+
logger_->Debug("[StaticDir]:static dir path error " +
119+
ctx.req().route().GetPath() + " " + path);
119120
ctx.resp().NotFound();
121+
ctx.Abort();
120122
return;
121123
}
122124
auto aim_path = route.substr(pos + path.size());
123125
// avoid path like /static/../xxx
124126
if (aim_path.find("..") != std::string::npos) {
125-
logger_->Warn("[logicerr]:static dir path error " + aim_path);
127+
logger_->Debug("[StaticDir]:static dir path error " + aim_path);
126128
ctx.resp().NotFound();
129+
ctx.Abort();
127130
return;
128131
}
129132
auto file_path = dir_path + "/" + aim_path;
130133
auto exist = File::Exist(file_path);
131134
if (!exist) {
132-
logger_->Warn("[logicerr]:static dir not exist " + file_path);
133-
ctx.Next();
135+
logger_->Debug("[StaticDir]:static dir not exist " + file_path);
134136
return;
135137
}
136138
auto rc = File::Read(file_path, ctx.resp().body());
137139
if (rc != kSuccess) {
138-
logger_->Error(file_path + " read error");
140+
logger_->Error("[StaticDir]:" + file_path + " read error");
139141
ctx.resp().NotFound();
142+
ctx.Abort();
140143
return;
141144
}
142-
logger_->Info("static_dir: return static dir success " + file_path);
145+
logger_->Debug("[StaticDir]: return static dir success " + file_path);
143146
ctx.resp().header().SetLongConnection(true);
144147
ctx.resp().Success(
145148
HttpHeader::ConvertFileType(File::Suffix(file_path)));
149+
ctx.Abort();
146150
},
147151
new_filters, false);
148152
if (rc != kSuccess) {
149-
logger_->Error("[logicerr]:register static dir error");
153+
logger_->Error("[StaticDir]:register static dir error");
150154
return rc;
151155
}
152156
return kSuccess;
@@ -164,29 +168,30 @@ int HttpGroup::StaticFile(
164168
[=](HttpContext &ctx) {
165169
auto exist = File::Exist(file_path);
166170
if (!exist) {
167-
logger_->Warn("[logicerr]:static file not exist " + file_path);
171+
logger_->Debug("[StaticFile]:static file not exist " + file_path);
168172
ctx.resp().NotFound();
169-
ctx.Next();
170173
return;
171174
}
172175
auto rc = File::Read(file_path, ctx.resp().body());
173176
if (rc != kSuccess) {
174-
logger_->Error("[logicerr]:" + file_path + " read error");
177+
logger_->Error("[StaticFile]:" + file_path + " read error");
175178
ctx.resp().NotFound();
179+
ctx.Abort();
176180
return;
177181
}
178-
logger_->Info("static_file: return static file success " + file_path);
182+
logger_->Debug("[StaticFile]: return static file success " + file_path);
179183
ctx.resp().header().SetLongConnection(true);
180184

181185
auto suffix = File::Suffix(file_path);
182186
auto type_str = HttpHeader::ConvertToStr(
183187
HttpHeader::ConvertFileType(suffix), suffix);
184188
ctx.resp().header().SetContentType(type_str);
185189
ctx.resp().Success();
190+
ctx.Abort();
186191
},
187192
new_filters);
188193
if (rc != kSuccess) {
189-
logger_->Error("[logicerr]:register static file error");
194+
logger_->Error("[StaticFile]:register static file error");
190195
return rc;
191196
}
192197
return kSuccess;
@@ -218,7 +223,7 @@ int HttpServer::Run() {
218223
logger_->Info("http server run in http://" + server_.addr().ToString());
219224
}
220225
#else
221-
logger_->Info("http server run in http://" + server_.addr().ToString());
226+
logger_->Debug("http server run in http://" + server_.addr().ToString());
222227
#endif
223228
auto rc = server_.EventLoop();
224229
if (rc != RC::kSuccess) {
@@ -251,8 +256,8 @@ void HttpServer::HandleAccept(TcpServer &server, Socket &event_soc) {
251256
event_soc.Close();
252257
return;
253258
}
254-
logger_->Info("accept from " + recv_addr.ToString() +
255-
" soc: " + std::to_string(event_soc.fd()));
259+
logger_->Debug("accept from " + recv_addr.ToString() +
260+
" soc: " + std::to_string(event_soc.fd()));
256261

257262
if (read_timeout_.first != 0 || read_timeout_.second != 0) {
258263
event_soc.SetReadTimeout(read_timeout_.first, read_timeout_.second);
@@ -278,8 +283,8 @@ void HttpServer::HandleAccept(TcpServer &server, Socket &event_soc) {
278283
void HttpServer::HandleLeave(TcpServer &server, Socket &event_soc) {
279284
Address recv_addr;
280285
event_soc.GetAddr(recv_addr);
281-
logger_->Info("leave from " + recv_addr.ToString() +
282-
" soc: " + std::to_string(event_soc.fd()));
286+
logger_->Debug("leave from " + recv_addr.ToString() +
287+
" soc: " + std::to_string(event_soc.fd()));
283288
#ifdef CPPNET_OPENSSL
284289
if (ssl_context_ &&
285290
ssl_sockets_map_.find(event_soc.fd()) != ssl_sockets_map_.end()) {
@@ -293,6 +298,9 @@ void HttpServer::HandleRead(TcpServer &server, Socket &event_soc) {
293298
const std::string kCRLF = "\r\n";
294299
const std::string kEndl = "\n";
295300
std::shared_ptr<Socket> soc = nullptr;
301+
Address recv_addr;
302+
event_soc.GetAddr(recv_addr);
303+
296304
#ifdef CPPNET_OPENSSL
297305
if (ssl_context_) {
298306
if (ssl_sockets_map_.find(event_soc.fd()) != ssl_sockets_map_.end()) {
@@ -340,7 +348,7 @@ void HttpServer::HandleRead(TcpServer &server, Socket &event_soc) {
340348
resp.BadRequest(req.err_msg());
341349
resp.Build(resp_buf);
342350
soc->Write(resp_buf);
343-
logger_->Info(
351+
logger_->Debug(
344352
"resp: " + HttpStatusCodeUtil::ConvertToStr(resp.status_code()) +
345353
" soc:" + std::to_string(event_soc.fd()) + kEndl);
346354
server.RemoveSoc(event_soc);
@@ -416,6 +424,12 @@ void HttpServer::HandleRead(TcpServer &server, Socket &event_soc) {
416424
soc->Close();
417425
return;
418426
}
427+
428+
// standardized log format
429+
logger_->Info("[cppnet] " + Date::GetNow() + " | " +
430+
std::to_string(int(resp.status_code())) + " | " +
431+
recv_addr.ToString() + " | " +
432+
HttpMethodUtil::ConvertToStr(method) + " | " + path);
419433
logger_->Debug(
420434
"resp: " + HttpStatusCodeUtil::ConvertToStr(resp.status_code()) +
421435
" soc:" + std::to_string(event_soc.fd()) + kEndl);

src/cppnet/utils/date.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#include "date.hpp"
2+
3+
#include <chrono>
4+
#include <ctime>
5+
#include <iomanip>
6+
#include <sstream>
7+
namespace cppnet {
8+
9+
std::string Date::GetNow(std::string format) {
10+
auto now = std::chrono::system_clock::now();
11+
std::time_t now_time = std::chrono::system_clock::to_time_t(now);
12+
std::tm local_tm;
13+
#ifdef _WIN32
14+
localtime_s(&local_tm, &now_time);
15+
#else
16+
localtime_r(&now_time, &local_tm);
17+
#endif
18+
19+
std::stringstream ss;
20+
ss << std::put_time(&local_tm, format.c_str());
21+
return ss.str();
22+
}
23+
24+
} // namespace cppnet

src/cppnet/utils/date.hpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#pragma once
2+
3+
#include <string>
4+
5+
namespace cppnet {
6+
class Date {
7+
public:
8+
/*
9+
* @brief Get the current date and time in the specified format
10+
* @param format The format of the date and time
11+
* @return The current date and time in the specified format
12+
* @note The default format is "%Y/%m/%d %H:%M:%S"
13+
*/
14+
static std::string GetNow(std::string format = "%Y/%m/%d %H:%M:%S");
15+
};
16+
} // namespace cppnet

0 commit comments

Comments
 (0)