Skip to content

Commit a9fffa0

Browse files
committed
Logging can now be configured
1 parent a55066b commit a9fffa0

9 files changed

+166
-116
lines changed

README.md

+39
Original file line numberDiff line numberDiff line change
@@ -178,3 +178,42 @@ build_flags =
178178
```
179179

180180
Note the `-D` in front of the actual flag name, that passes this flag as a definition to the preprocessor. Multiple flags can be added one per line.
181+
182+
### Configure Logging
183+
184+
The server provides some internal logging, which is used on level `INFO` by default. This will look like this on your serial console:
185+
186+
```
187+
[HTTPS:I] New connection. SocketFID=55
188+
[HTTPS:I] Request: GET / (FID=55)
189+
[HTTPS:I] Connection closed. Socket FID=55
190+
```
191+
192+
Logging output can also be controlled by using compiler flags. This requires an advanced development environment like explained in *Saving Space by Reducing Functionality*.
193+
194+
There are two parameters that can be configured:
195+
196+
- `HTTPS_LOGLEVEL` defines the log level to use
197+
- `HTTPS_LOGTIMESTAMP` adds a timestamp (based on uptime) to each log entry
198+
199+
| Value of `HTTPS_LOGLEVEL` | Error | Warning | Info | Debug |
200+
| ------------------------- | ----- | ------- | ---- | ----- |
201+
| 0 | | | | |
202+
| 1 || | | |
203+
| 2 ||| | |
204+
| 3 |||| |
205+
| 4 |||||
206+
207+
**Example: Configuration with Platform IO**
208+
209+
To set these flags in Platform IO, you can modify your `platformio.ini`. The following entries set the minimum log level to warning and enable timestamps
210+
211+
```ini
212+
[env:esp32dev]
213+
platform = espressif32
214+
board = esp32dev
215+
framework = arduino
216+
build_flags =
217+
-DHTTPS_LOGLEVEL=2
218+
-HTTPS_LOGTIMESTAMP
219+
```

src/HTTPConnection.cpp

+27-30
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,15 @@ int HTTPConnection::initialize(int serverSocketID, HTTPHeaders *defaultHeaders)
3737

3838
// Build up SSL Connection context if the socket has been created successfully
3939
if (_socket >= 0) {
40-
HTTPS_DLOGHEX("[-->] New connection. Socket fid is: ", _socket);
40+
HTTPS_LOGI("New connection. Socket FID=%d", _socket);
4141
_connectionState = STATE_INITIAL;
4242
_httpHeaders = new HTTPHeaders();
4343
refreshTimeout();
4444
return _socket;
4545

4646
}
4747

48-
HTTPS_DLOG("[ERR] Could not accept() new connection");
48+
HTTPS_LOGE("Could not accept() new connection");
4949

5050
_connectionState = STATE_ERROR;
5151
_clientState = CSTATE_ACTIVE;
@@ -110,7 +110,7 @@ void HTTPConnection::closeConnection() {
110110

111111
// Tear down the socket
112112
if (_socket >= 0) {
113-
HTTPS_DLOGHEX("[<--] Connection has been closed. fid = ", _socket);
113+
HTTPS_LOGI("Connection closed. Socket FID=%d", _socket);
114114
close(_socket);
115115
_socket = -1;
116116
_addrLen = 0;
@@ -121,13 +121,13 @@ void HTTPConnection::closeConnection() {
121121
}
122122

123123
if (_httpHeaders != NULL) {
124-
HTTPS_DLOG("[ ] Free headers");
124+
HTTPS_LOGD("Free headers");
125125
delete _httpHeaders;
126126
_httpHeaders = NULL;
127127
}
128128

129129
if (_wsHandler != nullptr) {
130-
HTTPS_DLOG("[ ] Freeing WS Handler");
130+
HTTPS_LOGD("Free WS Handler");
131131
delete _wsHandler;
132132
}
133133
}
@@ -165,7 +165,7 @@ int HTTPConnection::updateBuffer() {
165165
if (_bufferUnusedIdx < HTTPS_CONNECTION_DATA_CHUNK_SIZE) {
166166
if (canReadData()) {
167167

168-
HTTPS_DLOGHEX("[ ] There is data on the connection socket. fid=", _socket)
168+
HTTPS_LOGD("Data on Socket FID=%d", _socket);
169169

170170
int readReturnCode;
171171

@@ -188,13 +188,13 @@ int HTTPConnection::updateBuffer() {
188188
} else if (readReturnCode == 0) {
189189
// The connection has been closed by the client
190190
_clientState = CSTATE_CLOSED;
191-
HTTPS_DLOGHEX("[ x ] Client closed connection, fid=", _socket);
191+
HTTPS_LOGI("Client closed connection, FID=%d", _socket);
192192
// TODO: If we are in state websocket, we might need to do something here
193193
return 0;
194194
} else {
195195
// An error occured
196196
_connectionState = STATE_ERROR;
197-
HTTPS_DLOGHEX("[ERR] An receive error occured, fid=", _socket);
197+
HTTPS_LOGE("An receive error occured, FID=%d", _socket);
198198
closeConnection();
199199
return -1;
200200
}
@@ -261,7 +261,6 @@ size_t HTTPConnection::readBytesToBuffer(byte* buffer, size_t length) {
261261
void HTTPConnection::serverError() {
262262
_connectionState = STATE_ERROR;
263263

264-
Serial.println("Server error");
265264
char staticResponse[] = "HTTP/1.1 500 Internal Server Error\r\nServer: esp32https\r\nConnection:close\r\nContent-Type: text/html\r\nContent-Length:34\r\n\r\n<h1>500 Internal Server Error</h1>";
266265
writeBuffer((byte*)staticResponse, strlen(staticResponse));
267266
closeConnection();
@@ -271,7 +270,6 @@ void HTTPConnection::serverError() {
271270
void HTTPConnection::clientError() {
272271
_connectionState = STATE_ERROR;
273272

274-
Serial.println("Client error");
275273
char staticResponse[] = "HTTP/1.1 400 Bad Request\r\nServer: esp32https\r\nConnection:close\r\nContent-Type: text/html\r\nContent-Length:26\r\n\r\n<h1>400 Bad Request</h1>";
276274
writeBuffer((byte*)staticResponse, strlen(staticResponse));
277275
closeConnection();
@@ -290,7 +288,7 @@ void HTTPConnection::readLine(int lengthLimit) {
290288
return;
291289
} else {
292290
// Line has not been terminated by \r\n
293-
HTTPS_DLOG("[ERR] Line that has not been terminated by \\r\\n (got only \\r). Client error.");
291+
HTTPS_LOGW("Line without \\r\\n (got only \\r). FID=%d", _socket);
294292
clientError();
295293
return;
296294
}
@@ -302,7 +300,7 @@ void HTTPConnection::readLine(int lengthLimit) {
302300

303301
// Check that the max request string size is not exceeded
304302
if (_parserLine.text.length() > lengthLimit) {
305-
HTTPS_DLOG("[ERR] Line length exceeded. Server error.");
303+
HTTPS_LOGW("Header length exceeded. FID=%d", _socket);
306304
serverError();
307305
return;
308306
}
@@ -339,15 +337,15 @@ void HTTPConnection::loop() {
339337
updateBuffer();
340338

341339
if (_clientState == CSTATE_CLOSED) {
342-
HTTPS_DLOGHEX("[ ] Client closed in state", _clientState)
340+
HTTPS_LOGI("Client closed (FID=%d, cstate=%d)", _socket, _clientState);
343341
}
344342

345343
if (_clientState == CSTATE_CLOSED && _bufferProcessed == _bufferUnusedIdx && _connectionState < STATE_HEADERS_FINISHED) {
346344
closeConnection();
347345
}
348346

349347
if (!isClosed() && isTimeoutExceeded()) {
350-
HTTPS_DLOGHEX("[zZz] Connection timeout exceeded, closing connection. fid=", _socket)
348+
HTTPS_LOGI("Connection timeout. FID=%d", _socket);
351349
closeConnection();
352350
}
353351

@@ -360,7 +358,7 @@ void HTTPConnection::loop() {
360358
// Find the method
361359
size_t spaceAfterMethodIdx = _parserLine.text.find(' ');
362360
if (spaceAfterMethodIdx == std::string::npos) {
363-
HTTPS_DLOG("[ERR] Missing space after HTTP method. Client Error.")
361+
HTTPS_LOGW("Missing space after method");
364362
clientError();
365363
break;
366364
}
@@ -369,15 +367,15 @@ void HTTPConnection::loop() {
369367
// Find the resource string:
370368
size_t spaceAfterResourceIdx = _parserLine.text.find(' ', spaceAfterMethodIdx + 1);
371369
if (spaceAfterResourceIdx == std::string::npos) {
372-
HTTPS_DLOG("[ERR] Missing space after HTTP resource. Client Error.")
370+
HTTPS_LOGW("Missing space after resource");
373371
clientError();
374372
break;
375373
}
376374
_httpResource = _parserLine.text.substr(spaceAfterMethodIdx + 1, spaceAfterResourceIdx - _httpMethod.length() - 1);
377375

378376
_parserLine.parsingFinished = false;
379377
_parserLine.text = "";
380-
HTTPS_DLOG(("[ ] Request line finished: method="+_httpMethod+", resource="+_httpResource).c_str());
378+
HTTPS_LOGI("Request: %s %s (FID=%d)", _httpMethod.c_str(), _httpResource.c_str(), _socket);
381379
_connectionState = STATE_REQUEST_FINISHED;
382380
}
383381

@@ -389,7 +387,7 @@ void HTTPConnection::loop() {
389387
if (_parserLine.parsingFinished && _connectionState != STATE_ERROR) {
390388

391389
if (_parserLine.text.empty()) {
392-
HTTPS_DLOG("[ ] Headers finished");
390+
HTTPS_LOGD("Headers finished, FID=%d", _socket);
393391
_connectionState = STATE_HEADERS_FINISHED;
394392

395393
// Break, so that the rest of the body does not get flushed through
@@ -403,10 +401,9 @@ void HTTPConnection::loop() {
403401
_parserLine.text.substr(0, idxColon),
404402
_parserLine.text.substr(idxColon+2)
405403
));
406-
HTTPS_DLOG(("[ ] Header: " + _parserLine.text.substr(0, idxColon) + ":" + _parserLine.text.substr(idxColon+2)).c_str());
404+
HTTPS_LOGD("Header: %s = %s (FID=%d)", _parserLine.text.substr(0, idxColon).c_str(), _parserLine.text.substr(idxColon+2).c_str(), _socket);
407405
} else {
408-
HTTPS_DLOG("Malformed header line detected. Client error.");
409-
HTTPS_DLOG(_parserLine.text.c_str());
406+
HTTPS_LOGW("Malformed request header: %s", _parserLine.text.c_str());
410407
clientError();
411408
break;
412409
}
@@ -420,7 +417,7 @@ void HTTPConnection::loop() {
420417
break;
421418
case STATE_HEADERS_FINISHED: // Handle body
422419
{
423-
HTTPS_DLOG("[ ] Resolving resource...");
420+
HTTPS_LOGD("Resolving resource...");
424421
ResolvedResource resolvedResource;
425422

426423
// Check which kind of node we need (Websocket or regular)
@@ -445,10 +442,10 @@ void HTTPConnection::loop() {
445442
);
446443
}
447444
if (std::string("keep-alive").compare(connectionHeaderValue)==0) {
448-
HTTPS_DLOGHEX("[ ] Keep-Alive activated. fid=", _socket);
445+
HTTPS_LOGD("Keep-Alive activated. FID=%d", _socket);
449446
_isKeepAlive = true;
450447
} else {
451-
HTTPS_DLOGHEX("[ ] Keep-Alive disabled. fid=", _socket);
448+
HTTPS_LOGD("Keep-Alive disabled. FID=%d", _socket);
452449
_isKeepAlive = false;
453450
}
454451
} else {
@@ -505,7 +502,7 @@ void HTTPConnection::loop() {
505502
// However, if it does not, we need to clear the request body now,
506503
// because otherwise it would be parsed in the next request.
507504
if (!req.requestComplete()) {
508-
HTTPS_DLOG("[ERR] Callback function did not parse full request body");
505+
HTTPS_LOGW("Callback function did not parse full request body");
509506
req.discardRequestBody();
510507
}
511508

@@ -516,7 +513,7 @@ void HTTPConnection::loop() {
516513
_connectionState = STATE_WEBSOCKET;
517514
} else {
518515
// Handling the request is done
519-
HTTPS_DLOG("[ ] Handler function done, request complete");
516+
HTTPS_LOGD("Handler function done, request complete");
520517

521518
// Now we need to check if we can use keep-alive to reuse the SSL connection
522519
// However, if the client did not set content-size or defined connection: close,
@@ -548,7 +545,7 @@ void HTTPConnection::loop() {
548545
}
549546
} else {
550547
// No match (no default route configured, nothing does match)
551-
HTTPS_DLOG("[ERR] Could not find a matching resource. Server error.");
548+
HTTPS_LOGW("Could not find a matching resource");
552549
serverError();
553550
}
554551

@@ -563,12 +560,12 @@ void HTTPConnection::loop() {
563560
case STATE_WEBSOCKET: // Do handling of the websocket
564561
refreshTimeout(); // don't timeout websocket connection
565562
if(pendingBufferSize() > 0) {
566-
HTTPS_DLOG("[ ] websocket handler");
563+
HTTPS_LOGD("Calling WS handler, FID=%d", _socket);
567564
_wsHandler->loop();
568565
}
569566
// If the handler has terminated the connection, clean up and close the socket too
570567
if (_wsHandler->closed()) {
571-
HTTPS_DLOG("[ ] WS Connection closed. Freeing WS Handler");
568+
HTTPS_LOGI("WS closed, freeing Handler, FID=%d", _socket);
572569
delete _wsHandler;
573570
_wsHandler = nullptr;
574571
_connectionState = STATE_CLOSING;
@@ -589,7 +586,7 @@ bool HTTPConnection::checkWebsocket() {
589586
!_httpHeaders->getValue("Sec-WebSocket-Key").empty() &&
590587
_httpHeaders->getValue("Sec-WebSocket-Version") == "13") {
591588

592-
HTTPS_DLOG("[-->] Websocket detected");
589+
HTTPS_LOGI("Upgrading to WS, FID=%d", _socket);
593590
return true;
594591
} else
595592
return false;

src/HTTPHeader.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ namespace httpsserver {
55
HTTPHeader::HTTPHeader(const std::string &name, const std::string &value):
66
_name(name),
77
_value(value) {
8-
Serial.printf("Header Constructor: %s=%s\n4", name.c_str(), value.c_str());
8+
99
}
1010

1111
HTTPHeader::~HTTPHeader() {

src/HTTPResponse.cpp

+4-5
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
#include <Arduino.h>
44
#include "lwip/sockets.h"
55

6-
76
namespace httpsserver {
87

98
HTTPResponse::HTTPResponse(ConnectionContext * con):
@@ -18,10 +17,10 @@ HTTPResponse::HTTPResponse(ConnectionContext * con):
1817
_responseCacheSize = con->getCacheSize();
1918
_responseCachePointer = 0;
2019
if (_responseCacheSize > 0) {
21-
HTTPS_DLOGHEX("[ ] Creating buffered response. Buffer size: ", _responseCacheSize);
20+
HTTPS_LOGD("Creating buffered response, size: %d", _responseCacheSize);
2221
_responseCache = new byte[_responseCacheSize];
2322
} else {
24-
HTTPS_DLOG("[ ] Creating non-buffered response.")
23+
HTTPS_LOGD("Creating non-buffered response");
2524
_responseCache = NULL;
2625
}
2726
}
@@ -100,7 +99,7 @@ size_t HTTPResponse::write(uint8_t b) {
10099
*/
101100
void HTTPResponse::printHeader() {
102101
if (!_headerWritten) {
103-
HTTPS_DLOG("[ ] Printing headers")
102+
HTTPS_LOGD("Printing headers");
104103

105104
// Status line, like: "HTTP/1.1 200 OK\r\n"
106105
std::string statusLine = "HTTP/1.1 " + intToString(_statusCode) + " " + _statusText + "\r\n";
@@ -166,7 +165,7 @@ void HTTPResponse::drainBuffer(bool onOverflow) {
166165
}
167166

168167
if (_responseCache != NULL) {
169-
HTTPS_DLOG("[ ] Draining response buffer")
168+
HTTPS_LOGD("Draining response buffer");
170169
// Check for 0 as it may be an overflow reaction without any data that has been written earlier
171170
if(_responseCachePointer > 0) {
172171
// FIXME: Return value?

src/HTTPSConnection.cpp

+5-5
Original file line numberDiff line numberDiff line change
@@ -42,17 +42,17 @@ int HTTPSConnection::initialize(int serverSocketID, SSL_CTX * sslCtx, HTTPHeader
4242
if (success) {
4343
return resSocket;
4444
} else {
45-
HTTPS_DLOG("[ERR] SSL_accept failed. Aborting handshake.");
45+
HTTPS_LOGE("SSL_accept failed. Aborting handshake. FID=%d", resSocket);
4646
}
4747
} else {
48-
HTTPS_DLOG("[ERR] SSL_set_fd failed. Aborting handshake.");
48+
HTTPS_LOGE("SSL_set_fd failed. Aborting handshake. FID=%d", resSocket);
4949
}
5050
} else {
51-
HTTPS_DLOG("[ERR] SSL_new failed. Aborting handshake.");
51+
HTTPS_LOGE("SSL_new failed. Aborting handshake. FID=%d", resSocket);
5252
}
5353

5454
} else {
55-
HTTPS_DLOG("[ERR] Could not accept() new connection");
55+
HTTPS_LOGE("Could not accept() new connection. FID=%d", resSocket);
5656
}
5757

5858
_connectionState = STATE_ERROR;
@@ -93,7 +93,7 @@ void HTTPSConnection::closeConnection() {
9393
// The timeout has been hit, we force SSL shutdown now by freeing the context
9494
SSL_free(_ssl);
9595
_ssl = NULL;
96-
HTTPS_DLOG("[ERR] SSL_shutdown did not receive close notification from the client");
96+
HTTPS_LOGW("SSL_shutdown did not receive close notification from the client");
9797
_connectionState = STATE_ERROR;
9898
}
9999
}

0 commit comments

Comments
 (0)