Read log level from configuration and update readme

- Break out reading of settings in js and remove it from shell scripts
- Pick up config from Logger via Configuration class
This commit is contained in:
Victor Hagelbäck 2021-01-21 23:40:59 +01:00
parent 4176cfb714
commit 1b55cabf63
7 changed files with 90 additions and 34 deletions

View file

@ -104,6 +104,7 @@ mqttBroker | URL of the MQTT Broker, eg. mqtt://localhost
mqttUsername | Username of the MQTT broker
mqttPassword | Password of the MQTT broker
includeRoomsAsLights | Adds all rooms as lights, making it possible to turn on/off lights by room instead. Setting this to false will ignore all rooms. *Added in v. 5*.
logLevel | Minimim log level. Supported values are `error`, `warn`, `info`, `debug`, `verbose`, `silly` with increasing amount of logging. Do not log more than `info` for production purposes.
connectionTimeout | Number of seconds to wait when scanning and connecting. Might need to be tweaked on platforms other than RPi 4. Defaults to: 2 seconds.
writeQueueWaitTime | Wait time between message sent to Plejd over BLE, defaults to 400. If that doesn't work, try changing the value higher in steps of 50.
@ -128,6 +129,57 @@ https://www.home-assistant.io/integrations/google_assistant/
Check this out for more information on how you can get your Plejd lights controlled using HomeKit:
https://www.home-assistant.io/integrations/homekit/
## Logs
Logs are color coded and can be accessed on the Log tab of the addon. If you set log level to debug, verbose or silly you will generate a lot of log output
that will quickly scroll out of view. Logs can be exported through Docker that hosts all Home Assistant addons. To do that:
* SSH or console access the HA installation
* Identify the docker container name using `docker container ls` (NAMES column). Example name used `addon_local_plejd`
* tail logs: `tail -f addon_local_plejd`
* tail logs, strip color coding and save to file `docker logs -f addon_local_plejd | sed 's/\x1b\[[0-9;]*m//g' > /config/plejd.log` (output file might need to be adjusted)
### View logs in VS Code addon
Logs extracted as above can easily be viewed in the VS Code Home Assistant addon, which will default to using the excellent `Log File Highlighter` extension to parse the file.
Out of the box you can for example view elapsed time by selecting multiple lines and keeping an eye in the status bar. If you're feeling fancy you can get back the removed color information by adding something like below to the the `settings.json` configuration of VS Code.
```JSON
{
... other settings,
"logFileHighlighter.customPatterns": [
{
"pattern": "ERR",
"foreground": "#af1f1f",
"fontStyle": "bold",
},
{
"pattern": "WRN",
"foreground": "#af6f00",
"fontStyle": "bold",
},
{
"pattern": "INF",
"foreground": "#44d",
"fontStyle": "bold"
},
{
"pattern": "VRB",
"foreground": "#4a4",
},
{
"pattern": "DBG",
"foreground": "#4a4",
},
{
"pattern": "SIL",
"foreground": "#999"
},
{
"pattern": "\\[.*\\]",
"foreground": "#666"
}
]
}
```
## Changelog
*v 0.4.5*:
* FIX: Resolved a Docker build error

15
plejd/Configuration.js Normal file
View file

@ -0,0 +1,15 @@
const fs = require('fs');
class Configuration {
static _config = null;
static getConfiguration() {
if (!Configuration._config) {
const rawData = fs.readFileSync('/data/options.json');
Configuration._config = JSON.parse(rawData);
}
return Configuration._config;
}
}
module.exports = Configuration;

View file

@ -10,6 +10,7 @@ SHELL ["/bin/bash", "-o", "pipefail", "-c"]
COPY ./api.js /plejd/
COPY ./ble.bluez.js /plejd/
COPY ./config.json /plejd/
COPY ./Configuration.js /plejd/
COPY ./Logger.js /plejd/
COPY ./main.js /plejd/
COPY ./mqtt.js /plejd/

View file

@ -1,6 +1,10 @@
const winston = require("winston");
const { colorize, combine, label, printf, timestamp } = winston.format;
const Configuration = require("./Configuration");
const LEVELS = ["error", "warn", "info", "debug", "verbose", "silly"];
const logFormat = printf(info => {
if(info.stack) {
return `${info.timestamp} ${info.level} [${info.label}] ${info.message}\n${info.stack}`;
@ -19,11 +23,17 @@ class Logger {
* - swap debug/verbose levels and omit http to mimic HA standard
* Levels (in order): error, warn, info, debug, verbose, silly
* */
static getLogger(moduleName, level="verbose") {
static getLogger(moduleName) {
const config = Configuration.getConfiguration();
const level = (config.logLevel && LEVELS.find(l => l.startsWith(config.logLevel[0].toLowerCase()))) || "info";
const logger = winston.createLogger({
format: combine(
winston.format(info => {
switch (info.level) {
case "warning":
info.level = "WRN";
break;
case "verbose":
info.level = "VRB";
break;
@ -48,6 +58,12 @@ class Logger {
]
});
winston.addColors(Logger.logLevels().colors);
if (moduleName === "plejd-main") {
logger.log(level, `Log level set to ${level}`);
}
return logger;
}

View file

@ -24,6 +24,7 @@
"mqttUsername": "",
"mqttPassword": "",
"includeRoomsAsLights": false,
"logLevel": "info",
"connectionTimeout": 2,
"writeQueueWaitTime": 400
},
@ -35,6 +36,7 @@
"mqttUsername": "str",
"mqttPassword": "str",
"includeRoomsAsLights": "bool",
"logLevel": "str",
"connectionTimeout": "int",
"writeQueueWaitTime": "int"
}

View file

@ -1,10 +1,10 @@
const api = require('./api');
const mqtt = require('./mqtt');
const fs = require('fs');
const Logger = require('./Logger');
const PlejdService = require('./ble.bluez');
const SceneManager = require('./scene.manager');
const Configuration = require("./Configuration");
const logger = Logger.getLogger("plejd-main");
@ -14,8 +14,7 @@ const version = "0.4.8";
async function main() {
logger.info(`Starting Plejd add-on v. ${version}`);
const rawData = fs.readFileSync('/data/plejd.json');
const config = JSON.parse(rawData);
const config = Configuration.getConfiguration();
if (!config.connectionTimeout) {
config.connectionTimeout = 2;

View file

@ -1,33 +1,4 @@
#!/usr/bin/with-contenv bashio
CONFIG_PATH=/data/options.json
SITE=$(jq --raw-output ".site" $CONFIG_PATH)
USERNAME=$(jq --raw-output ".username" $CONFIG_PATH)
PASSWORD=$(jq --raw-output ".password" $CONFIG_PATH)
MQTTBROKER=$(jq --raw-output ".mqttBroker" $CONFIG_PATH)
MQTTUSERNAME=$(jq --raw-output ".mqttUsername" $CONFIG_PATH)
MQTTPASSWORD=$(jq --raw-output ".mqttPassword" $CONFIG_PATH)
INCLUDEROOMSASLIGHTS=$(jq --raw-output ".includeRoomsAsLights" $CONFIG_PATH)
CONNECTIONTIMEOUT=$(jq --raw-output ".connectionTimeout" $CONFIG_PATH)
WRITEQUEUEWAITTIME=$(jq --raw-output ".writeQueueWaitTime" $CONFIG_PATH)
PLEJD_PATH=/data/plejd.json
PLEJD_CONFIG="{
\"site\": \"$SITE\",
\"username\": \"$USERNAME\",
\"password\": \"$PASSWORD\",
\"mqttBroker\": \"$MQTTBROKER\",
\"mqttUsername\": \"$MQTTUSERNAME\",
\"mqttPassword\": \"$MQTTPASSWORD\",
\"includeRoomsAsLights\": \"$INCLUDEROOMSASLIGHTS\",
\"connectionTimeout\": \"$CONNECTIONTIMEOUT\",
\"writeQueueWaitTime\": \"$WRITEQUEUEWAITTIME\"
}
"
bashio::log.info 'Wrote plejd.json'
echo "$PLEJD_CONFIG" > $PLEJD_PATH
bashio::log.info 'Running add-on'
exec node /plejd/main.js