So I'm looking to create a log file for my discord bot which is built with python.
I have a few set commands which output the the console through the print command, I have added a date and time to the print outputs so it can be tracked when the bot is running, however is it easy to make it save the print outs to a file as well? That way I can make a log file to track different days and what was called for.
Console Output: Screenshot_1.png
Example of a print command in my code:
async def coin(ctx):
author = ctx.message.author
choice = random.randint(1,2)
if choice == 1:
await bot.say("Heads")
print(currentTime() + " - Coin Requested by " + str(author) + " It Landed on Heads!")
elif choice == 2:
await bot.say("Tails")
print(currentTime() + " - Coin Requested by " + str(author) + " It Landed on Tails!")
I have tried looking online at some other questions but I get quite confused looking at them as there is no clear explanation as to whats happening and how I can configure it to work for my code.
The simple way is to use the function above. This code avoid the duplicate logs and to run more than one log file;
Logging in python is very efficient and easy to use. You just have to define a python module for logging using python internal logging module. You can define as many logger as you want. You can also configure it to print the output to a console as well write to a file. Apart from this you can define a rotating file handler which will do a log rotation as well which helps in log rotation automation. Below is the snippet to directly define and call the logger in any python module.
once you have defined this file (say logger_settings.py), you can import it anywhere and use.
Hope this help. Thanks
To create the log file we can use logging package in python. Code to create log file -
And if you want to create the log file timestamp than we can accomplish that using datetime package. code to create log file with timestamp -
You can use the
logging
module to accomplish this.At the very easiest level, it will be set up like this:
There are a number of different levels that you can use to write to the file, such as:
You can use these lines anywhere that you want to log to the file. If you want to replace the console printing with logging all together, just replace the print lines with
logging.info(.......)
For more info on the topic, such as more configurable options (such as timestamps), check the docs: https://docs.python.org/2/library/logging.html