From ed21dc4b6e7d88be7671747decc22eb04a6ad568 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=98=95=20Tim?= Date: Mon, 5 Feb 2024 22:42:16 +1000 Subject: [PATCH] Add option to allow logging to standard error Sometimes you'd like to be able to influence the log lines and send some logs to standard error. This option add the property `LOG_TO_STANDARD_ERROR` which will send any failing status codes to standard error. --- README.md | 10 ++++++++++ index.js | 10 ++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 65d9064..6bac5c6 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,16 @@ You can disable new lines in the log output by setting the environment variable docker run -e LOG_WITHOUT_NEWLINE=true -p 8080:8080 -p 8443:8443 --rm -t mendhak/http-https-echo:31 ``` +## Log to standard error + +By default the log output is always sent to standard out. If you want to vary the log output format you can set `LOG_TO_STANDARD_ERROR` which combined with `x-set-response-status-code` will log anything with a status code between 400 and 599, to standard error. + +```bash +docker run -e LOG_TO_STANDARD_ERROR=true -p 8080:8080 -p 8443:8443 --rm -t mendhak/http-https-echo:31 + +curl -v -H "x-set-response-status-code: 401" http://localhost:8080/ +``` + ## Send an empty response You can disable the JSON output in the response by setting the environment variable `ECHO_BACK_TO_CLIENT`. For example, diff --git a/index.js b/index.js index 03391c1..d62d99e 100644 --- a/index.js +++ b/index.js @@ -131,11 +131,17 @@ app.all('*', (req, res) => { if (process.env.LOG_IGNORE_PATH != req.path) { let spacer = 4; - if(process.env.LOG_WITHOUT_NEWLINE){ + if(process.env.LOG_WITHOUT_NEWLINE) { spacer = null; } - console.log(JSON.stringify(echo, null, spacer)); + //Allow logging to standard error if the status code is a failure + let loggerFunction = console.log; + if (process.env.LOG_TO_STANDARD_ERROR === "true" && setResponseStatusCode >= 400 && setResponseStatusCode < 600) { + loggerFunction = console.error; + } + + loggerFunction(JSON.stringify(echo, null, spacer)); } });