创建一个日志文件 [英] Create a log file

查看:77
本文介绍了创建一个日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在为使用Python构建的Discord机器人创建日志文件.

So I'm looking to create a log file for my discord bot which is built with python.

我有一些设置命令,这些命令通过print命令输出控制台,我在打印输出中添加了日期和时间,以便可以在机器人运行时对其进行跟踪,但是很容易使其保存打印输出到文件?这样,我可以制作一个日志文件来跟踪不同的日子和要求的日期.

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.

控制台输出: 屏幕截图_1.png

我的代码中的打印命令示例:

Example of a print command in my code:

异步def硬币(ctx):

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.

推荐答案

您可以使用logging模块来完成此操作.

You can use the logging module to accomplish this.

在最简单的级别上,其设置如下:

At the very easiest level, it will be set up like this:

logging.basicConfig(filename="logfilename.log", level=logging.INFO)

您可以使用许多不同的级别来写入文件,例如:

There are a number of different levels that you can use to write to the file, such as:

logging.info('your text goes here')
logging.error('your text goes here')
logging.debug('your text goes here')

您可以在要登录到文件的任何位置使用这些行.如果要用全部一起记录替换控制台打印,只需用logging.info(.......)

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

有关该主题的更多信息,例如更多可配置的选项(例如时间戳记),请检查以下文档: https://docs.python.org/2/library/logging.html

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

这篇关于创建一个日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆