Skip to content

Commit

Permalink
Add more logs
Browse files Browse the repository at this point in the history
  • Loading branch information
LunaUrsa committed Apr 29, 2024
1 parent d9e2f9a commit 324dac7
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 90 deletions.
7 changes: 4 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"trivia-api": "^1.0.0",
"underscore": "^1.13.6",
"winston": "^3.11.0",
"winston-transport": "^4.7.0",
"winston-transport-rollbar-3": "^3.2.6",
"youtube-search-without-api-key": "^2.0.1"
},
Expand Down
192 changes: 105 additions & 87 deletions src/global/utils/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ import {
addColors,
Logger,
} from 'winston';
import Transport from 'winston-transport';
// import { Logtail } from '@logtail/node'; // eslint-disable-line
// import { LogtailTransport } from '@logtail/winston'; // eslint-disable-line
import Rollbar, { Level } from 'rollbar';
// import SentryTransport from 'winston-transport-sentry-node'; // eslint-disable-line
import * as Sentry from '@sentry/node';
import { ConsoleTransportInstance } from 'winston/lib/winston/transports';
import { env } from './env.config';

// const RollbarTransport = require('winston-transport-rollbar-3');

const {
combine,
splat,
Expand All @@ -30,103 +30,127 @@ addColors({
debug: 'blue',
});

const myFormat = printf(({
level, message, timestamp, stack, ...metadata // eslint-disable-line
}) => {
let msg = '';
if (env.NODE_ENV === 'production') {
msg += '(Prd) ';
} else {
msg += `(Dev) ${timestamp} `;
}
class DiscordTransport extends Transport {
async log(info: any, callback: () => void) {
setImmediate(() => {
this.emit('logged', info);
});

// This makes it so that the logs look nice and even
// Idk why the length is 15, maybe cuz of colors
if (level.length < 15) {
msg += `${level} `;
} else {
msg += `${level} `;
}
if (!global.discordClient || !discordClient.isReady()) {
if (callback) callback();
return;
}

msg += `${message} `;
const prefixDict = {
error: '❌',
warn: '⚠️',
info: 'ℹ️',
debug: '🐛',
http: '🌐',
} as {
[key: string]: string;
};

try {
const channel = await discordClient.channels.fetch(env.CHANNEL_BOTERRORS);
if (!channel) return;
if (!channel.isTextBased()) return;
await channel.send(`${prefixDict[info.level]} ${info.message}`);
} catch (error) {
console.error('Failed to send message to Discord:', error);
}

if (JSON.stringify(metadata) !== '{}') {
console.debug(`metadata: ${JSON.stringify(metadata, null, 2)}`); // eslint-disable-line no-console
msg += JSON.stringify(metadata);
}
if (stack) {
console.debug(`stack: ${stack}`); // eslint-disable-line no-console
msg += `\n${stack}`;
if (callback) {
callback();
}
}
return msg;
});

// Old sentry stuff
// const sentryConfig = {
// dsn: env.SENTRY_TOKEN,
// debug: true, // Enable debug mode to log internal transactions
// // level: 'error',
// tracesSampleRate: 1.0,
// // environment: env.NODE_ENV,
// // integrations: [
// // // enable HTTP calls tracing
// // new Sentry.Integrations.Http({ tracing: true }),
// // // Automatically instrument Node.js libraries and frameworks
// // ...Sentry.autoDiscoverNodePerformanceMonitoringIntegrations(),
// // ],
// };

// console.log(`sentryConfig: ${JSON.stringify(sentryConfig)}`); // eslint-disable-line no-console

// Sentry.init(sentryConfig);

// const sentryTransportConfig = {
// sentry: sentryConfig,
// skipSentryInit: true,
// level: 'error',
// };

// global.sentry = Sentry;

// const transaction = Sentry.startTransaction({
// op: 'test',
// name: 'My First Test Transaction',
// });

// setTimeout(() => {
// try {
// console.log('foo');
// // @ts-ignore
// foo(); // eslint-disable-line
// console.log('bar');
// } catch (e) {
// console.log('error');
// Sentry.captureException(e);
// } finally {
// transaction.finish();
// }
// }, 99);
}

const transportOptions = [
new transports.Console(),
new transports.Console({
format: combine(
format.colorize({ all: true }),
splat(),
timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
printf(({
level, message, timestamp, stack, ...metadata // eslint-disable-line
}) => {
let msg = '';
if (env.NODE_ENV === 'production') {
msg += '(Prd) ';
} else {
msg += `(Dev) ${timestamp} `;
}

// This makes it so that the logs look nice and even
// Idk why the length is 15, maybe cuz of colors
if (level.length < 15) {
msg += `${level} `;
} else {
msg += `${level} `;
}

msg += `${message} `;

if (JSON.stringify(metadata) !== '{}') {
console.debug(`metadata: ${JSON.stringify(metadata, null, 2)}`); // eslint-disable-line no-console
msg += JSON.stringify(metadata);
}
if (stack) {
console.debug(`stack: ${stack}`); // eslint-disable-line no-console
msg += `\n${stack}`;
}
return msg;
}),
),
}),
];

// We only want rollbar logs in production
// let transportOptions = [];
if (env.NODE_ENV === 'production') {
transportOptions.push(new DiscordTransport({
format: combine(
printf(({
level, message, timestamp, stack, ...metadata // eslint-disable-line
}) => {
let msg = '';
if (env.NODE_ENV === 'production') {
msg += '(Prd) ';
} else {
msg += `(Dev) ${timestamp} `;
}

// This makes it so that the logs look nice and even
// Idk why the length is 15, maybe cuz of colors
if (level.length < 15) {
msg += `${level} `;
} else {
msg += `${level} `;
}

msg += `${message} `;

if (JSON.stringify(metadata) !== '{}') {
console.debug(`metadata: ${JSON.stringify(metadata, null, 2)}`); // eslint-disable-line no-console
msg += JSON.stringify(metadata);
}
if (stack) {
console.debug(`stack: ${stack}`); // eslint-disable-line no-console
msg += `\n${stack}`;
}
return msg;
}),
),
}) as ConsoleTransportInstance);
const rollbarConfig = {
accessToken: env.ROLLBAR_TOKEN,
// captureUncaught: true,
// captureUnhandledRejections: true,
logLevel: 'error' as Level,
};

// transportOptions.push(new RollbarTransport({ rollbarConfig }));
// Setup Rollbar

global.rollbar = new Rollbar(rollbarConfig);

// Setup glitchTip
// Setup Sentry
Sentry.init({
dsn: env.GLITCHTIP_DSN,
// debug: true,
Expand All @@ -136,12 +160,6 @@ if (env.NODE_ENV === 'production') {

const logger = createLogger({
level: env.DEBUG_LEVEL,
format: combine(
format.colorize({ all: true }),
splat(),
timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
myFormat,
),
transports: transportOptions,
});

Expand Down

0 comments on commit 324dac7

Please sign in to comment.