python 记录配置文件_Python记录基本配置

python 记录配置文件

To configure the python logging module, to set the log level, log format, etc., we can use the basicConfig(**kwargs) method where **kwargs in the function definition means this function takes variable length arguments, which should be passed in the key-value form.

配置 python日志记录模块,设置日志级别,日志格式等,我们可以使用basicConfig(**kwargs)方法,其中函数定义中的**kwargs表示此函数采用可变长度参数 ,应将其传递以键值形式。

Some commonly used parameters in the basicConfig() function is given below:

下面给出了basicConfig()函数中的一些常用参数:

  • level: With the help of this parameter the root logger will be set to the specified severity level, like DEBUG, INFO, ERROR, etc.

    level :借助此参数,根记录器设置为指定的严重性级别,例如DEBUG,INFO,ERROR等。

  • filename: This parameter is mainly used to specify the file name if we want to store the logs in a file.

    filename :如果我们要将日志存储在文件中,则此参数主要用于指定文件名

  • filemode: If the filename is given, the file is opened in this mode. The default mode is a, which means append.

    filemode :如果提供了filenamefilemode 该模式打开文件 。 默认模式是a ,这意味着append

  • format: This is used to specify the format of the log message. For example, if you want to add timestamp with the logs, or the name of the python script or maybe the function or class name in the logs, then we can specify the appropriate format for that.

    format :用于指定日志消息的格式 。 例如,如果您想在日志中添加时间戳,或者在日志中添加python脚本的名称或函数或类的名称,那么我们可以为此指定适当的格式。

In the basicConfig() function we can either provide the level parameter with an appropriate value, filename and filecode for printing logs in file, and the format parameter to specify the logs, or you can specify all the parameters together, that is the beauty of **kwargs, which means the number of arguments that can be supplied to a function is not fixed.

basicConfig()函数中,我们可以为level参数提供适当的值, 文件名文件 代码以在文件中打印日志, 还可以为format参数指定日志,或者可以一起指定所有参数,这就是**kwargs ,这意味着可以提供给函数的参数数量不是固定的。

让我们举个例子 (Let's take an Example)

Let us take a look at the example for the clear understanding of this method:

让我们看一下示例,以清楚地了解此方法:

import logging

logging.basicConfig(level=logging.INFO)
logging.info('This is an info message.This will get logged.')

INFO:root: This is an info message. This will get logged.

INFO:root:这是一条信息消息。 这将被记录。

All events at or above INFO level will now get logged.

现在将记录INFO级别或更高级别的所有事件。

要记住的要点: (Points to remember:)

  • It is important to note here that calling basicConfig() to configure the root logger works in the case only if the root logger has not been configured before. Basically, this function can only be called once.

    在此需要注意的重要一点是,只有在之前未配置根记录器的情况下,调用basicConfig()才能配置根记录器 。 基本上,此函数只能调用一次。

  • Also debug(), info(), warning(), error(), and critical(), all these functions internally call basicConfig() method without any arguments automatically if it has not been called before.

    还有debug()info()warning()error()critical() ,所有这些函数在内部都调用basicConfig()方法, 如果以前没有调用过该方法, 则该方法将不带任何参数自动进行

  • This means that after the first time one of the above-given functions is called, you can no longer configure the root logger because they would have called the basicConfig() function internally.

    这意味着在第一次调用上述函数之一之后,您将无法再配置根记录器,因为它们会在内部调用basicConfig()函数。

Thus the default setting in basicConfig() is to set the logger to write to the console in the following format:

因此, basicConfig()的默认设置是将记录器设置为以以下格式写入控制台:

ERROR:root: This is an error message

错误:root:这是一条错误消息

With log level, logger name and then the log message.

使用日志级别,记录器名称,然后是日志消息。

将日志存储在文件中 (Store Logs in File)

We can use the basicConfig() method to store logs in a file. How we can do so, we will learn in the next tutorial where we will cover how to store Python code logs in a file.

我们可以使用basicConfig()方法将日志存储在文件中。 如何执行此操作,我们将在下一个教程中学习如何覆盖将Python代码日志存储在文件中的内容

设置日志格式 (Set Format of Logs)

We can configure the logging module to print logs in a any format we want. There are some standard formats which are universally used, and we can configure the python logger to print logs in those formats.

我们可以将日志记录模块配置为以所需的任何格式打印日志。 有一些通用的标准格式,我们可以配置python记录器以这些格式打印日志。

There are some basic components of logs that are already a part of the LogRecord and we can easily add them or remove them from the output format.

日志中已有一些基本组件 ,它们已经成为LogRecord的一部分,我们可以轻松地添加它们或将它们从输出格式中删除。

Let's take a few examples to understand this.

让我们举几个例子来理解这一点。

将进程ID添加到带有日志级别和消息的日志中 (Add process ID to logs with loglevel and message)

If you want to include the process ID for the running python script along with the log level and message then the code snippet for the same is given below:

如果要包括正在运行的python脚本的进程ID以及日志级别和消息,则下面提供了相同的代码段:

import logging

logging.basicConfig(format='%(process)d-%(levelname)s-%(message)s')
logging.warning('This message is a warning')


1396-WARNING-This message is a warning


1396-WARNING-此消息是警告

In the code above, in the basicConfig() method, we have set the format parameter with the format string as value in which we have specified, what components we want in our log, along with specifying its datatype, like d with process to print the integer process Id, then s for loglevel which is string value, and same for the message

在上面的代码中,在basicConfig()方法中,我们使用格式字符串将format参数设置为我们在其中指定的值,在日志中需要什么组件,并指定了其数据类型 ,例如d带有要打印的进程整数进程ID,然后s ,即loglevel ,它是字符串值,与消息相同

Also, in the code above, we can set the format with the LogRecord attributes set in any order.

同样,在上面的代码中,我们可以使用以任意顺序设置的LogRecord属性来设置格式。

将时间戳添加到带有日志消息的日志中 (Add Timestamp to logs with log message)

You can also add date and time info(timestamp) to your logs along with the log message. The code snippet for the same is given below:

您还可以将日期和时间信息(时间戳)以及日志消息一起添加到日志中。 相同的代码段如下所示:

import logging

logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)
logging.info('This message is to indicate that Admin has just logged in')


2020-06-19 11:43:59,887 - This message is to indicate that Admin has just logged in


2020-06-19 11:43:59,887-此消息表明管理员刚刚登录

In the above code %(asctime)s adds the time of the creation of the LogRecord. Also, we have configured the log level too with code level=logging.INFO.

在上面的代码%(asctime)s添加了LogRecord的创建时间。 另外,我们还使用代码level=logging.INFO配置了日志级别。

使用datefmt属性 (Use the datefmt attribute)

You can also change the format using the datefmt attribute, which uses the same formatting language as the formatting functions in the datetime module, such as time.strftime():

您还可以使用datefmt属性更改格式 ,该属性使用 datetime模块中的格式化函数相同的格式化语言 ,例如time.strftime()

import logging

logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
logging.warning('The Admin just logged out')


19-Jun-20 11:50:28 - The Admin just logged out


20-Jun-20 11:50:28-管理员刚刚注销

As you can see the log printed as the output of the above code has a date format DD-MMM-YY along with time.

如您所见,上面代码的输出显示的日志具有日期格式DD-MMM-YY和时间。

So, using the basicConfig(**kwargs) method, we can configure the logs format as we want, like adding timestamp to logs, adding process id to logs, printing log level along with logs and log messages.

因此,使用basicConfig(**kwargs)方法,我们可以根据需要配置日志格式,例如向日志中添加时间戳,向日志中添加进程ID,打印日志级别以及日志和日志消息。

翻译自: https://www.studytonight.com/python/python-logging-configuration

python 记录配置文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值