登录Python

在本文中,我们将学习有关使用Python登录以及保护和安全性的各个阶段的信息。

首先,我们需要导入日志记录模块,然后使用记录器检查当前状态和日志消息。我们有5个严重等级,即-

  • 警告

  • 信息

  • 错误

  • 危急

  • 除错

日志记录模块使我们可以直接开始,而无需手动设置配置。

示例

Import logging
logging.debug('a debug message')
logging.info('an info message')
logging.warning('a warning message')
logging.error('an error message')
logging.critical('a critical message')

输出结果

WARNING:root: a warning message
ERROR:root: an error message
CRITICAL:root: a critical message

由于我们未设置配置,因此默认情况下不会记录日志记录和信息消息。为了使它们引人注目,我们需要手动设置配置。

现在让我们看看如何实现基本配置。

借助级别参数-我们可以设置必须记录的日志消息级别。

示例

Import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This gets logged')

输出结果

DEBUG:root: This gets logged

通过使用此语句,将记录调试级别以上的所有语句。

现在通过控制台日志记录切换到文件日志记录。

示例

Import logging
logging.basicConfig(filename='app.log', filemode='w',
format='%(name)s - %(levelname)s - %(message)s')
logging.warning('This gets logged to a file')

输出结果

root - ERROR - This gets logged to a file

在这里,文件模式被称为只写,因此我们有权重写文件的内容。默认情况下,此配置仅在附加模式下打开。

结论

在本文中,我们了解了Python日志记录以及可供我们使用的各种级别的日志记录。