ivanmarban / winston-telegram Goto Github PK
View Code? Open in Web Editor NEWA Telegram transport for winston
License: MIT License
A Telegram transport for winston
License: MIT License
[email protected] start /usr/src/app
node index.js trade
/usr/src/app/node_modules/winston-telegram/lib/winston-telegram.js:46
this.handleExceptions = options.handleExceptions ?? true
^
SyntaxError: Unexpected token ?
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object. (/usr/src/app/src/modules/services.js:46:31)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: node index.js trade
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /root/.npm/_logs/2022-10-09T03_06_21_437Z-debug.log
# npm audit report
striptags <3.2.0
Severity: moderate
Passing in a non-string 'html' argument can lead to unsanitized output - https://github.com/advisories/GHSA-qxg5-2qff-p49r
fix available via `npm audit fix --force`
Will install [email protected], which is a breaking change
node_modules/striptags
utils >=0.3.1
Depends on vulnerable versions of striptags
node_modules/utils
sf >=0.2.0
Depends on vulnerable versions of utils
node_modules/sf
winston-telegram 1.3.1 - 2.3.5 || >=2.4.1
Depends on vulnerable versions of sf
node_modules/winston-telegram
import * as TelegramLogger from 'winston-telegram' throws: "TypeError: TelegramLogger is not a constructor"
It works with: import TelegramLogger from 'winston-telegram'
Tested on node v16.13.2
"winston": "3.7.2",
"winston-telegram": "2.5.0"
Function for send messages to telegram.
const logger = async function (level, error) {
try {
if (['info', 'error'].indexOf(level) !== -1) {
await sendToTelegram(
level,
error.name,
error.message,
error.fileName,
error.lineNumber,
error.columnNumber,
error.stack,
);
}
} catch (e) {
console.log(e);
}
};
const sendToTelegram = function send(level = '-', name = '-',
info = '-', fileName = '-', lineNumber = 0,
columnNumber = 0, stack = '-') {
const dateMsg = new Date();
const dateMsgFormat = `
${dateMsg.getHours()}:${dateMsg.getMinutes()}:${dateMsg.getSeconds()}
${dateMsg.getDay()}.${dateMsg.getMonth()}.${dateMsg.getFullYear()}
`
.replace(/\r?\n/g, "")
.replace(/\s{2,}/g, ' ');
if (incrementCounter()) {
loggerWinston.log({
level: level,
message: 'level: ' + String(level) + '\n' +
'data: ' + String(dateMsgFormat) + '\n' +
'name: ' + String(name) + '\n' +
'information: ' + String(info + ' ') + '\n' +
'file name: ' + String(fileName) + '\n' +
'line number: ' + Number(lineNumber) + '\n' +
'column number: ' + Number(columnNumber) + '\n'
'stack: ' + String(stack)
});
}
};
When i call her,
logger('info', {name: 'Информационное сообщение', message: 'Информационное сообщение с BackEnd'});
I get an error.
Error [ERR_UNHANDLED_ERROR]: Unhandled error. ('400: Bad Request: message text is empty')
But, when I comment line, it works.
loggerWinston.log({
level: level,
message: 'level: ' + String(level) + '\n' +
'data: ' + String(dateMsgFormat) + '\n' +
'name: ' + String(name) + '\n' +
//'information: ' + String(info + ' ') + '\n' + // commnent line
'file name: ' + String(fileName) + '\n' +
'line number: ' + Number(lineNumber) + '\n' +
'column number: ' + Number(columnNumber) + '\n'
'stack: ' + String(stack)
});
When sending many request during a certain timeframe, the Telegram API reacts with a HTTP 429 Error code (too many requests):
events.js:306
throw err; // Unhandled 'error' event
^
Error [ERR_UNHANDLED_ERROR]: Unhandled error. ('429: Too Many Requests: retry after 5')
at DerivedLogger.emit (events.js:304:17)
at DerivedLogger.transportEvent (/usr/src/app/node_modules/winston/lib/winston/logger.js:630:12)
at Telegram.emit (events.js:327:22)
at /usr/src/app/node_modules/winston-telegram/lib/winston-telegram.js:133:14
at IncomingMessage.<anonymous> (/usr/src/app/node_modules/winston-telegram/lib/winston-telegram.js:155:9)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'ERR_UNHANDLED_ERROR',
context: '429: Too Many Requests: retry after 5'
}
Is there a recommended way to handle rate limiting issues?
This is an option for chats with threads enabled.
message_thread_id | Integer | Optional. Unique identifier of a message thread to which the message belongs; for supergroups only |
---|
Hello, thanks for the awesome project!
I have an issue with the long messages as all unhandled exceptions from the server are sent to telegram.
For example:
logger.error("1".repeat(5000));
Logger.error is used for logging messages to telegram.
This line throws the following exception:
[error] uncaughtException: Unhandled error. ('400: Bad Request: message is too long')
Error [ERR_UNHANDLED_ERROR]: Unhandled error. ('400: Bad Request: message is too long')
at new NodeError (node:internal/errors:371:5)
at DerivedLogger.emit (node:events:383:17)
at DerivedLogger.transportEvent (/project-path/node_modules/winston/lib/winston/logger.js:630:12)
at Telegram.emit (node:events:406:35)
at /project-path/node_modules/winston-telegram/lib/winston-telegram.js:133:14
at IncomingMessage.<anonymous> (/project-path/node_modules/winston-telegram/lib/winston-telegram.js:155:9)
at IncomingMessage.emit (node:events:406:35)
at endReadableNT (node:internal/streams/readable:1343:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
The message should be split after 4096 characters to fix unexpected logging exceptions.
For now, I'm using the following technique to cut the message:
formatMessage: function (options) {
let message = options.message;
if (message.length > 4000) {
message = message.substring(0, 4000);
}
return message;
},
I have winston configuration with telegram.
const logger = winston.createLogger({
format: winston.format.json(),
transports: [
new TelegramLogger({
token: '...',
chatId: '...',
level: 'info',
unique: true
}),
new TelegramLogger({
token: '...',
chatId: '...',
level: 'error',
unique: true
})
]
});
Function send message
const sendToTelegram = function send(level, message) {
logger.log({
level: level,
message: message
});
};
Route for logger
router.post('/logger', async (req, res) => {
try {
if (['info', 'error'].indexOf(req.body.level) !== -1 && req.body.token === '...') {
const dateLog = new Date();
await sendToTelegram(
req.body.level,
`
${dateLog.getHours()}:${dateLog.getMinutes()}:${dateLog.getSeconds()}
${dateLog.getDay()}.${dateLog.getMonth()}.${dateLog.getFullYear()}
${req.body.message}
`
.replace(/\r?\n/g, "")
.replace(/\s{2,}/g, ' ')
);
res.status(200).json({status: 'ok'});
} catch(e) {
const err = {
info: e
};
res.status(500).json(err);
}
}
After sending the request with Postman, i getting message "status": "ok".
But after a few seconds in the console I see an error:
Error: connect ETIMEDOUT 149.154.167.220:443
[nodemon] app crashed - waiting for file changes before starting...
How to properly handle errors ?
It is posible?
I try:
formatMessage: options => {
let message = options.message;
message = `\`\`\`${message}\`\`\``;
return message;
},
End message looks like this:
```Test error```
'['+level+'] '
is added to each log message. However, in some cases we like to not see that . Can you remove the log_level_label it or make it a config option ?
Use case: we use "alert" in same channel as "error" ... but alerts are not an error... Or you have better idea how to do alerts?
logger.add(winston.transports.Telegram, {
level: 'warning',
token: env.TELEGRAM_LOGGER_BOT_TOKEN,
chatid: env.TELEGRAM_LOGGER_BOT_CHAT_ID
});
Both messages were logged (but should only one):
logger.info('Application started');
logger.warn('Application started');
This is a work around, how to set log level. After such configuration only warning are presents.
logger.transports.undefined.level = 'warning';
Issues:
logger.transports
Great idea!
Would it be possible to use different log levels going to different channels? I'd like warnings go to notify-silent Telegram channels, but send errors to a Telegram channel that give me a notification...
Hi, I get this error while importing without using the esModuleInterop
flag.
> tsc
node_modules/winston-telegram/lib/winston-telegram.d.ts:1:8 - error TS1259: Module '"D:/Projects/project/node_modules/winston-transport/index"' can only be default-imported using the 'esModuleInterop' flag
1 import TransportStream from "winston-transport"
~~~~~~~~~~~~~~~
node_modules/winston-transport/index.d.ts:37:1
37 export = TransportStream;
~~~~~~~~~~~~~~~~~~~~~~~~~
This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.
Shouldn't winston-trasport
be imported with =
?
Doing exactly as said in the description, I get:
WARNING in ./~/winston/lib/winston/transports.js
Critical dependencies:
23:17-34 the request of a dependency is an expression
@ ./~/winston/lib/winston/transports.js 23:17-34
WARNING in ./~/winston/~/colors/lib/colors.js
Critical dependencies:
127:29-43 the request of a dependency is an expression
@ ./~/winston/~/colors/lib/colors.js 127:29-43
WARNING in ./~/winston/~/colors/lib/extendStringPrototype.js
Critical dependencies:
106:31-45 the request of a dependency is an expression
@ ./~/winston/~/colors/lib/extendStringPrototype.js 106:31-45
ERROR in ./~/winston/lib/winston/common.js
Module not found: Error: Cannot resolve module 'fs' in ~/my_project/node_modules/winston/lib/winston
@ ./~/winston/lib/winston/common.js 12:9-22
ERROR in ./~/pkginfo/lib/pkginfo.js
Module not found: Error: Cannot resolve module 'fs' in ~/my_project/node_modules/pkginfo/lib
@ ./~/pkginfo/lib/pkginfo.js 8:9-22
ERROR in ./~/winston/lib/winston/transports/file.js
Module not found: Error: Cannot resolve module 'fs' in ~/my_project/node_modules/winston/lib/winston/transports
@ ./~/winston/lib/winston/transports/file.js 10:9-22
ERROR in ./~/request/lib/har.js
Module not found: Error: Cannot resolve module 'fs' in ~/my_project/node_modules/request/lib
@ ./~/request/lib/har.js 3:9-22
ERROR in ./~/forever-agent/index.js
Module not found: Error: Cannot resolve module 'net' in ~/my_project/node_modules/forever-agent
@ ./~/forever-agent/index.js 6:10-24
ERROR in ./~/forever-agent/index.js
Module not found: Error: Cannot resolve module 'tls' in ~/my_project/node_modules/forever-agent
@ ./~/forever-agent/index.js 7:10-24
ERROR in ./~/tough-cookie/lib/cookie.js
Module not found: Error: Cannot resolve module 'net' in ~/my_project/node_modules/tough-cookie/lib
@ ./~/tough-cookie/lib/cookie.js 32:10-24
ERROR in ./~/tunnel-agent/index.js
Module not found: Error: Cannot resolve module 'net' in ~/my_project/node_modules/tunnel-agent
@ ./~/tunnel-agent/index.js 3:10-24
ERROR in ./~/tunnel-agent/index.js
Module not found: Error: Cannot resolve module 'tls' in ~/my_project/node_modules/tunnel-agent
@ ./~/tunnel-agent/index.js 4:10-24
Seem all dependency problems? As per issue #3 npm install -save vows
did not help at all.
I find this (and slack transport) very useful- but only in a handful of cases, where I need to announce something important. Otherwise it becomes impossible with all the noise. I may be blind but AFAIK there isn't anything the library provides, to make it possible to selectively send some messages to TG. For instance, I'm wanting to do this:
// something horrible happened, send help
logger.debug('Red Alert!', { chatId: process.env.TEAM_CHAT_ID })
I think maybe it can identify the parameter in the metadata object, and when that's present, use the transport. Is this possible to your knowledge? Thanks!
After npm install -save winston
I get on running npm install -save winston-telegram
:
├── UNMET PEER DEPENDENCY vows@
└── [email protected]
I looked at vows
and dont think I want it. Is it needed? Can we get it out?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.