Coder Social home page Coder Social logo

ivanmarban / winston-telegram Goto Github PK

View Code? Open in Web Editor NEW
38.0 1.0 21.0 996 KB

A Telegram transport for winston

License: MIT License

JavaScript 97.06% Dockerfile 2.94%
telegram winston-transport logger winstonjs node-js node telegram-bot logging-library winston3

winston-telegram's People

Contributors

alberto467 avatar arnidan avatar azliabdullah avatar batformat avatar dutu avatar ivanmarban avatar justinong avatar meleshyn avatar mrnix avatar multivit4min avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

winston-telegram's Issues

Multiple Log-Levels

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...

Feature request - message labels

'['+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?

Please, update dependencies

# 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

Winston Transport can only be default-imported using the 'esModuleInterop' flag

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 =?

this.handleExceptions = options.handleExceptions ?? true

[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

Output in markdown format?

It is posible?

I try:

formatMessage: options => {
        let message = options.message;
        message = `\`\`\`${message}\`\`\``;
        return message;
      },

End message looks like this:
```Test error```

Setting log level to warn doesn't work

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:

  1. Setting log level to warn doesn't work
  2. Telegram transport name is 'undefined' on logger.transports

How to properly handle errors in nuxt ?

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 ?

[Suggestion/FR] Selective logging to telegram

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!

Update readme

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"

How to fix 400 error ?

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)
    });

Unmet Peer Dependency

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?

429: Too Many Requests: retry after 5

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?

Split long messages

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;
    },

Bunch of errors

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.