Imporved logger

This commit is contained in:
unknown 2021-06-22 14:49:00 +02:00
parent 5ae4d6e7c4
commit e3ed429da1
12 changed files with 89 additions and 55 deletions

View file

@ -1,2 +1,3 @@
node_modules node_modules
github github
public

5
.gitignore vendored
View file

@ -1,2 +1,3 @@
node_modules/ node_modules
data/ data
public

View file

@ -1,11 +1,13 @@
const WebSocket = require('ws'); const WebSocket = require('ws');
const Logger = require('./utils/Logger');
const logger = new Logger();
class Socket { class Socket {
constructor(server) { constructor(server) {
this.webSocketServer = new WebSocket.Server({ server }) this.webSocketServer = new WebSocket.Server({ server })
this.webSocketServer.on('listening', () => { this.webSocketServer.on('listening', () => {
console.log('Socket: listen'); logger.log('Socket: listen');
}) })
this.webSocketServer.on('connection', (webSocketClient) => { this.webSocketServer.on('connection', (webSocketClient) => {

View file

@ -1 +1 @@
REACT_APP_VERSION=1.4.1 REACT_APP_VERSION=1.4.2

View file

@ -1,17 +1,28 @@
import { useState, useEffect, ChangeEvent, FormEvent } from 'react'; import { useState, useEffect, ChangeEvent, FormEvent } from 'react';
import axios from 'axios'; import axios from 'axios';
// Redux
import { connect } from 'react-redux';
import { createNotification } from '../../../store/actions';
// Typescript
import { ApiResponse, NewNotification } from '../../../interfaces';
// UI
import InputGroup from '../../UI/Forms/InputGroup/InputGroup'; import InputGroup from '../../UI/Forms/InputGroup/InputGroup';
import Button from '../../UI/Buttons/Button/Button'; import Button from '../../UI/Buttons/Button/Button';
import { ApiResponse } from '../../../interfaces';
const StyleSettings = (): JSX.Element => { interface ComponentProps {
createNotification: (notification: NewNotification) => void;
}
const StyleSettings = (props: ComponentProps): JSX.Element => {
const [customStyles, setCustomStyles] = useState<string>(''); const [customStyles, setCustomStyles] = useState<string>('');
useEffect(() => { useEffect(() => {
axios.get<ApiResponse<string>>('/api/config/0/css') axios.get<ApiResponse<string>>('/api/config/0/css')
.then(data => setCustomStyles(data.data.data)) .then(data => setCustomStyles(data.data.data))
.catch(err => console.log(err)); .catch(err => console.log(err.response));
}, []) }, [])
const inputChangeHandler = (e: ChangeEvent<HTMLTextAreaElement>) => { const inputChangeHandler = (e: ChangeEvent<HTMLTextAreaElement>) => {
@ -22,7 +33,14 @@ const StyleSettings = (): JSX.Element => {
const formSubmitHandler = (e: FormEvent) => { const formSubmitHandler = (e: FormEvent) => {
e.preventDefault(); e.preventDefault();
axios.put<ApiResponse<{}>>('/api/config/0/css', { styles: customStyles }); axios.put<ApiResponse<{}>>('/api/config/0/css', { styles: customStyles })
.then(() => {
props.createNotification({
title: 'Success',
message: 'CSS saved. Reload page to see changes'
})
})
.catch(err => console.log(err.response));
} }
return ( return (
@ -34,6 +52,7 @@ const StyleSettings = (): JSX.Element => {
name='customStyles' name='customStyles'
value={customStyles} value={customStyles}
onChange={(e) => inputChangeHandler(e)} onChange={(e) => inputChangeHandler(e)}
spellCheck={false}
></textarea> ></textarea>
</InputGroup> </InputGroup>
<Button>Save CSS</Button> <Button>Save CSS</Button>
@ -41,4 +60,4 @@ const StyleSettings = (): JSX.Element => {
) )
} }
export default StyleSettings; export default connect(null, { createNotification })(StyleSettings);

15
db.js
View file

@ -1,4 +1,6 @@
const { Sequelize } = require('sequelize'); const { Sequelize } = require('sequelize');
const Logger = require('./utils/Logger');
const logger = new Logger();
const sequelize = new Sequelize({ const sequelize = new Sequelize({
dialect: 'sqlite', dialect: 'sqlite',
@ -9,17 +11,18 @@ const sequelize = new Sequelize({
const connectDB = async () => { const connectDB = async () => {
try { try {
await sequelize.authenticate(); await sequelize.authenticate();
console.log('Connected to database'); logger.log('Connected to database');
const syncModels = false;
const syncModels = true;
if (syncModels) { if (syncModels) {
console.log('Starting model synchronization'); logger.log('Starting model synchronization');
await sequelize.sync({ alter: true }); await sequelize.sync({ alter: true });
console.log('All models were synchronized'); logger.log('All models were synchronized');
} }
} catch (error) { } catch (error) {
throw new Error(`Unable to connect to the database: ${error.message}`); logger.log(`Unable to connect to the database: ${error.message}`, 'ERROR');
process.exit(1);
} }
} }

View file

@ -1,5 +1,7 @@
const ErrorResponse = require('../utils/ErrorResponse'); const ErrorResponse = require('../utils/ErrorResponse');
const colors = require('colors'); const colors = require('colors');
const Logger = require('../utils/Logger');
const logger = new Logger();
const errorHandler = (err, req, res, next) => { const errorHandler = (err, req, res, next) => {
let error = { ...err }; let error = { ...err };
@ -10,8 +12,7 @@ const errorHandler = (err, req, res, next) => {
// error = new ErrorResponse(`Field ${msg}`, 400); // error = new ErrorResponse(`Field ${msg}`, 400);
// } // }
console.log(error); logger.log(error.message.split(',')[0], 'ERROR');
console.log(`${err}`);
res.status(err.statusCode || 500).json({ res.status(err.statusCode || 500).json({
success: false, success: false,

View file

@ -7,6 +7,8 @@ const Socket = require('./Socket');
const Sockets = require('./Sockets'); const Sockets = require('./Sockets');
const associateModels = require('./models/associateModels'); const associateModels = require('./models/associateModels');
const initConfig = require('./utils/initConfig'); const initConfig = require('./utils/initConfig');
const Logger = require('./utils/Logger');
const logger = new Logger();
const PORT = process.env.PORT || 5005; const PORT = process.env.PORT || 5005;
@ -24,6 +26,6 @@ const PORT = process.env.PORT || 5005;
Sockets.registerSocket('weather', weatherSocket); Sockets.registerSocket('weather', weatherSocket);
server.listen(PORT, () => { server.listen(PORT, () => {
console.log(`Server is running on port ${PORT} in ${process.env.NODE_ENV} mode`); logger.log(`Server is running on port ${PORT} in ${process.env.NODE_ENV} mode`);
}) })
})(); })();

View file

@ -1,40 +1,39 @@
const fs = require('fs');
class Logger { class Logger {
constructor() { log(message, level = 'INFO') {
this.logFileHandler(); console.log(`[${this.generateTimestamp()}] [${level}] ${message}`)
} }
logFileHandler() { generateTimestamp() {
if (!fs.existsSync('./flame.log')) { const d = new Date();
fs.writeFileSync('./flame.log', '');
} else { // Date
console.log('file exists'); const year = d.getFullYear();
const month = this.parseDate(d.getMonth() + 1);
const day = this.parseDate(d.getDate());
// Time
const hour = this.parseDate(d.getHours());
const minutes = this.parseDate(d.getMinutes());
const seconds = this.parseDate(d.getSeconds());
const miliseconds = this.parseDate(d.getMilliseconds(), true);
// Timezone
const tz = -d.getTimezoneOffset() / 60;
return `${year}-${month}-${day} ${hour}:${minutes}:${seconds}.${miliseconds} UTC${tz > 0 ? '+' + tz : tz}`;
}
parseDate(date, ms = false) {
if (ms) {
if (date >= 10 && date < 100) {
return `0${date}`;
} else if (date < 10) {
return `00${date}`;
}
} }
}
writeLog(logMsg, logType) { return date < 10 ? `0${date}` : date.toString();
}
generateLog(logMsg, logType) {
const now = new Date();
const date = `${this.parseNumber(now.getDate())}-${this.parseNumber(now.getMonth() + 1)}-${now.getFullYear()}`;
const time = `${this.parseNumber(now.getHours())}:${this.parseNumber(now.getMinutes())}:${this.parseNumber(now.getSeconds())}.${now.getMilliseconds()}`;
const log = `[${date} ${time}]: ${logType} ${logMsg}`;
return log;
// const timestamp = new Date().toISOString();
}
parseNumber(number) {
if (number > 9) {
return number;
} else {
return `0${number}`;
}
} }
} }
// console.log(logger.generateLog('testMsg', 'INFO')); module.exports = Logger;
module.exports = new Logger();

View file

@ -1,5 +1,7 @@
const { Op } = require('sequelize'); const { Op } = require('sequelize');
const Weather = require('../models/Weather'); const Weather = require('../models/Weather');
const Logger = require('./Logger');
const logger = new Logger();
const clearWeatherData = async () => { const clearWeatherData = async () => {
const weather = await Weather.findOne({ const weather = await Weather.findOne({
@ -16,7 +18,7 @@ const clearWeatherData = async () => {
}) })
} }
console.log('Old weather data was deleted'); logger.log('Old weather data was deleted');
} }
module.exports = clearWeatherData; module.exports = clearWeatherData;

View file

@ -1,6 +1,8 @@
const { Op } = require('sequelize'); const { Op } = require('sequelize');
const Config = require('../models/Config'); const Config = require('../models/Config');
const { config } = require('./initialConfig.json'); const { config } = require('./initialConfig.json');
const Logger = require('./Logger');
const logger = new Logger();
const initConfig = async () => { const initConfig = async () => {
// Get config values // Get config values
@ -26,7 +28,7 @@ const initConfig = async () => {
} }
}) })
console.log('Initial config created'); logger.log('Initial config created');
return; return;
} }

View file

@ -2,15 +2,17 @@ const schedule = require('node-schedule');
const getExternalWeather = require('./getExternalWeather'); const getExternalWeather = require('./getExternalWeather');
const clearWeatherData = require('./clearWeatherData'); const clearWeatherData = require('./clearWeatherData');
const Sockets = require('../Sockets'); const Sockets = require('../Sockets');
const Logger = require('./Logger');
const logger = new Logger();
// Update weather data every 15 minutes // Update weather data every 15 minutes
const weatherJob = schedule.scheduleJob('updateWeather', '0 */15 * * * *', async () => { const weatherJob = schedule.scheduleJob('updateWeather', '0 */15 * * * *', async () => {
try { try {
const weatherData = await getExternalWeather(); const weatherData = await getExternalWeather();
console.log('weather updated'); logger.log('Weather updated');
Sockets.getSocket('weather').socket.send(JSON.stringify(weatherData)); Sockets.getSocket('weather').socket.send(JSON.stringify(weatherData));
} catch (err) { } catch (err) {
console.log(err.message); logger.log(err.message, 'ERROR');
} }
}) })