Package: python-logging-discord-handler
Python logging handler for DiscordRedirect your Python log output to Discord usingPython logging subsystemandDiscord Webhook library.Use casesEasily share logs with non-technical colleaguesGet notified on server-side errorsFollow your batch job processes easilyGood for businesses and communities that have their messaging set up in DiscordFeaturesMinimum or no changes to a Python application neededOptional color coding of messages usingDiscord embedsOptional emoticons on messages using UnicodeDiscord rate limiting friendly for burst of logsDocumentationSpecial handling for long log messages like tracebacks to deal with Discord's 2000 character max message lengthRequirementsPython 3.8+InstallationWith pip:pipinstallpython-logging-discord-handlerWith Poetry:poetryaddpython-logging-discord-handlerUsageThis example logs both to Discord and standard output.First you need toimportloggingfromdiscord_logging.handlerimportDiscordHandler# See instructions below how to get a Webhook URLwebhook_url=# ...logger=logging.getLogger()stream_format=logging.Formatter("%(asctime)s-%(name)s-%(levelname)s-%(message)s")discord_format=logging.Formatter("%(message)s")discord_handler=DiscordHandler("Hello World Bot",webhook_url,avatar_url="https://i0.wp.com/www.theterminatorfans.com/wp-content/uploads/2012/09/the-terminator3.jpg?resize=900%2C450&ssl=1")#discord_handler = DiscordHandler("Happy Bot", webhook_url, emojis={})discord_handler.setFormatter(discord_format)stream_handler=logging.StreamHandler()stream_handler.setFormatter(stream_format)# Add the handlers to the Loggerlogger.addHandler(discord_handler)logger.addHandler(stream_handler)logger.setLevel(logging.DEBUG)logger.info("This is an info message")logger.debug("A debug message - usually not that interesting")logger.error("Very nasty error messgae!")Find more examples in the examples.py source code.How to get Discord webhook URLGo toEdit channel(gear) in DiscordChooseIntegrationsChooseView webhooks->NewCopy URLWebhook URL securityIt is recommend that you store the webhook URL outside your source code to avoid damage in hacks or similar security incidents.In Linux/macOS shell you can do on the command line:exportDISCORD_TEST_WEBHOOK_URL=<yourwebhookURLhere>For long term configuration, you can create a file storing environment variables outside your source code tree, like in your home directory. Store theexportcommands there.# Text editor for a secrets.env file in your home directory on Linuxnano~/secrets.envIn your Linux shell session, you can then read this file and make environment variables effective usingsourcecommand in your shell:# Reads secrets.env and executes all commands there and makes them effective# in the current shell sessionsource~/secrets.envThen you can read the environment variable in your Python code:importoswebhook_url=os.environ["DISCORD_TEST_WEBHOOK_URL"]Discord limitationsMax 2000 characters per message. See API documentation how to work around this limitation with different options. By default the bottom most lines of the log message, like a traceback, are shown.Discord embeds, those that give you a logging level color bar on the left, have very hard time to deal with long lines. Embeds are disabled for long lines by default.Log output formatting logicThe log message are converted to Discord embeds with the following logicSingle line log messsages are converted to embed titlesFor multi line log messages, the first line is the embed title and the following lines are the embed descriptionLong lines or long messages cannot be convert to embeds, instead they useDiscord Markdown code formattiongto preserve the readability of the outputA specialmessage_break_charcan be assigned to manually split long messagesColours and emoticonsLogging messages can be decorated with colours and emoticons.Here are the defaults:#: The default log level colors as hexacimal, converted intDEFAULT_COLOURS={None:2040357,# Unknown log levellogging.CRITICAL:14362664,# Redlogging.ERROR:14362664,# Redlogging.WARNING:16497928,# Yellowlogging.INFO:2196944,# Bluelogging.DEBUG:8947848,# Gray}#: The default log emojis asDEFAULT_EMOJIS={None:"",# Unknown log levellogging.CRITICAL:"🆘",logging.ERROR:"❌",logging.WARNING:"⚠️",logging.INFO:"",logging.DEBUG:"",}Emoticons are disabled by default as they often make the output a bit too colourful and harder to read.Testing and developmentManual testsInspect how logging output looks in Discord.Checkout this Git repositorySet up a dummy Discord channelGet its webhook URLpoetryinstall-EdocsexportDISCORD_TEST_WEBHOOK_URL=...
pythondiscord_logging/examples.pyThis will dump some messages to your Discord.Automated testsRun:pytestHistoryOriginally created for Trading Strategyto follow trading bot activity.LicenseMIT