Created
August 17, 2025 21:12
-
-
Save martin2844/9e7ddc28d92481b3e30322af2404cf12 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { WebhookClient } from 'discord.js'; | |
const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL as string; | |
class DiscordLogger { | |
private webhook: WebhookClient | null = null; | |
constructor() { | |
// Only initialize webhook in Node.js environment | |
if (process.env.NEXT_RUNTIME === 'nodejs' && !process.env.IS_ARM) { | |
if (!DISCORD_WEBHOOK_URL) { | |
console.error('DISCORD_WEBHOOK_URL is not set'); | |
return; | |
} | |
this.webhook = new WebhookClient({ url: DISCORD_WEBHOOK_URL }); | |
} | |
} | |
private formatMessage(message: any): string { | |
if (typeof message === 'string') { | |
return message; | |
} | |
return '```json\n' + JSON.stringify(message, null, 2) + '\n```'; | |
} | |
private async sendToDiscord(content: string) { | |
// Skip if not in Node.js environment | |
if (!this.webhook) { | |
console.log('Discord logging skipped - not in Node.js environment'); | |
return; | |
} | |
try { | |
await this.webhook.send({ | |
content: content.substring(0, 2000), // Discord has a 2000 character limit | |
}); | |
} catch (error) { | |
console.error('Failed to send message to Discord:', error); | |
} | |
} | |
info(message: any) { | |
this.sendToDiscord(`[info] ${this.formatMessage(message)}`).catch(console.error); | |
} | |
error(message: string, error?: Error | unknown) { | |
let formattedMessage = `[error] ${message}\n`; | |
if (error) { | |
formattedMessage += '```\n'; | |
if (error instanceof Error) { | |
formattedMessage += `${error.message}\n${error.stack || ''}`; | |
} else { | |
formattedMessage += JSON.stringify(error, null, 2); | |
} | |
formattedMessage += '\n```'; | |
} | |
this.sendToDiscord(formattedMessage).catch(console.error); | |
} | |
warn(message: any) { | |
this.sendToDiscord(`[warn] ${this.formatMessage(message)}`).catch(console.error); | |
} | |
debug(message: any) { | |
if (process.env.NODE_ENV === 'development') { | |
this.sendToDiscord(`[debug] ${this.formatMessage(message)}`).catch(console.error); | |
} | |
} | |
} | |
// Export a singleton instance | |
export const log = new DiscordLogger(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment