Logging system added

This commit is contained in:
Lucas Gabriel 2024-06-02 01:38:25 -03:00
parent 784a463e8e
commit 945182329e
No known key found for this signature in database
GPG Key ID: D9B075FC6DC93985
2 changed files with 48 additions and 7 deletions

41
src/logger.js Normal file
View File

@ -0,0 +1,41 @@
const fs = require('fs');
const util = require('util');
const logFile = 'log.txt';
const logStream = fs.createWriteStream(logFile, { flags: 'a' });
const getFormattedDate = () => {
const date = new Date();
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
const hours = ('0' + date.getHours()).slice(-2);
const minutes = ('0' + date.getMinutes()).slice(-2);
const seconds = ('0' + date.getSeconds()).slice(-2);
return `[${year}-${month}-${day} ${hours}:${minutes}:${seconds}]`;
};
const logMessage = async (message) => {
const timestamp = getFormattedDate();
const formattedMessage = `${timestamp} ${util.format(message)}`;
process.stdout.write(formattedMessage + '\n');
return new Promise((resolve, reject) => {
logStream.write(formattedMessage + '\n', (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
console.log = (message) => {
logMessage(message).catch(err => {
process.stderr.write(`Error writing to log: ${err}\n`);
});
};
module.exports = logMessage;

View File

@ -1,18 +1,18 @@
const TelegramBot = require('node-telegram-bot-api');
const fs = require('fs');
const path = require('path');
const token = process.env.TGBOT_TOKEN; // config.env
const logMessage = require('./logger');
const token = process.env.TGBOT_TOKEN;
const bot = new TelegramBot(token, { polling: true });
const commandsPath = path.join(__dirname, 'commands')
const commandsPath = path.join(__dirname, 'commands');
const commandHandlers = {};
// load all commands
fs.readdirSync(commandsPath).forEach(file => {
const command = `/${path.parse(file).name}`;
const handler = require(path.join(commandsPath,file));
const handler = require(path.join(commandsPath, file));
commandHandlers[command] = handler;
})
});
bot.on('message', (msg) => {
const messageText = msg.text;
@ -25,5 +25,5 @@ bot.on('polling_error', (error) => {
console.error('Polling error:', error);
});
const date = Date();
console.log(`INFO: Lynx started at: \n${date}\n`)
const date = new Date().toString();
console.log(`INFO: Lynx started\n`);