Python 创建日志文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49580313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:09:22  来源:igfitidea点击:

Create a log file

pythonpython-3.xlogging

提问by Kynakuu

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

所以我想为我的不和谐机器人创建一个日志文件,它是用 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

控制台输出: Screenshot_1.png

Example of a print command in my code:

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

async def coin(ctx):

异步定义硬币(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.

我曾尝试在网上查看其他一些问题,但看着它们我感到很困惑,因为没有明确解释发生了什么以及如何配置它以适用于我的代码。

回答by Harrison

You can use the loggingmodule to accomplish this.

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

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')

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

您可以在要记录到文件的任何位置使用这些行。如果要将控制台打印替换为一起记录,只需将打印行替换为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

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

回答by Brijesh Rana

To create the log file we can use logging package in python. Code to create log file -

要创建日志文件,我们可以使用 python 中的 logging 包。创建日志文件的代码 -

import logging
LOG_FILENAME = "logfile.log"
for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)    
logging.info('Forecastiong Job Started...')
logging.debug('abc method started...')

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 -

如果你想创建日志文件时间戳,我们可以使用 datetime 包来完成。使用时间戳创建日志文件的代码 -

from datetime import datetime
LOG_FILENAME = datetime.now().strftime('D:/log/logfile_%H_%M_%S_%d_%m_%Y.log')

回答by Tasneem Haider

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.

登录python非常高效且易于使用。你只需要定义一个 python 模块来使用 python 内部日志记录模块进行日志记录。您可以根据需要定义任意数量的记录器。您还可以将其配置为将输出打印到控制台以及写入文件。除此之外,您可以定义一个旋转文件处理程序,它也将执行日志轮换,这有助于日志轮换自动化。下面是在任何 python 模块中直接定义和调用记录器的代码片段。

import sys
import logging
from logging.config import dictConfig

logging_config = dict(
    version=1,
    formatters={
        'verbose': {
            'format': ("[%(asctime)s] %(levelname)s "
                       "[%(name)s:%(lineno)s] %(message)s"),
            'datefmt': "%d/%b/%Y %H:%M:%S",
        },
        'simple': {
            'format': '%(levelname)s %(message)s',
        },
    },
    handlers={
        'api-logger': {'class': 'logging.handlers.RotatingFileHandler',
                           'formatter': 'verbose',
                           'level': logging.DEBUG,
                           'filename': 'logs/api.log',
                           'maxBytes': 52428800,
                           'backupCount': 7},
        'batch-process-logger': {'class': 'logging.handlers.RotatingFileHandler',
                             'formatter': 'verbose',
                             'level': logging.DEBUG,
                             'filename': 'logs/batch.log',
                             'maxBytes': 52428800,
                             'backupCount': 7},
        'console': {
            'class': 'logging.StreamHandler',
            'level': 'DEBUG',
            'formatter': 'simple',
            'stream': sys.stdout,
        },
    },
    loggers={
        'api_logger': {
            'handlers': ['api-logger', 'console'],
            'level': logging.DEBUG
        },
        'batch_process_logger': {
            'handlers': ['batch-process-logger', 'console'],
            'level': logging.DEBUG
        }
    }
)

dictConfig(logging_config)

api_logger = logging.getLogger('api_logger')
batch_process_logger = logging.getLogger('batch_process_logger')

once you have defined this file (say logger_settings.py), you can import it anywhere and use.

一旦你定义了这个文件(比如 logger_settings.py),你就可以将它导入到任何地方并使用。

from logger_settings import api_logger

api_logger.info('hello world')

Hope this help. Thanks

希望这有帮助。谢谢