python日志记录_Python日志记录

python日志记录

To start, logging is a way of tracking events in a program when it runs and is in execution. Python logging module defines functions and classes that provide a flexible event logging system for python applications.

首先,日志记录是一种在程序运行和执行时跟踪其事件的方法。 Python日志记录模块定义了为python应用程序提供灵活的事件日志记录系统的函数

Python记录模块 (Python Logging Module)

Logging information while events happen is a handy task which helps to see the pattern in which our program executes, what data it acted upon and what results it returned and all this is done without affecting the actual state of the program.

在事件发生时记录信息是一项方便的任务,它有助于查看程序的执行模式,所作用的数据以及返回的结果,并且所有这些操作都不会影响程序的实际状态。

Note that the logs are only for developers (usually) and they can be visualized using many tools. Let’s look into different aspects of python logging module now.

请注意,这些日志通常仅适用于开发人员,并且可以使用许多工具进行可视化。 现在让我们研究python日志记录模块的不同方面。

Python记录级别 (Python Logging Levels)

Each log message is assigned a level of severity. Broadly speaking, there are following python logging levels:

每个日志消息都分配有一个严重性级别。 概括地说,有以下python日志记录级别:

  • Info: It is used to log useful infor about app lifecycle and these logs won’t metter under normal circumstances .

    信息 :它用于记录有关应用程序生命周期的有用信息,这些日志在正常情况下不会起作用。
  • Warn: Use this log level when an event can potentially cause application abnormalities but are handled in the code ourself.

    警告 :当事件可能导致应用程序异常但由我们自己的代码处理时,请使用此日志级别。
  • Error: Any log message which was fatal to the normal flow of execution of the program but not related to the the application state itself.

    错误 :任何对程序的正常执行流程致命但与应用程序状态本身无关的日志消息。
  • Debug: This is used just to log diagnosis information like system health and is useful to people like system admins etc.

    调试 :此命令仅用于记录诊断信息(例如系统运行状况),对系统管理员等人员很有用。
  • Fatal/Critical: These are errors which is forcing a shutown for the application and required immediate developer/admin intervention. This may also mean data loss or corruption of some kind.

    致命/严重 :这些错误迫使应用程序无法正常运行,并且需要开发人员/管理员立即进行干预。 这也可能意味着某种形式的数据丢失或损坏。

More or less they are very similar to java log4j logging framework.

它们或多或少与Java log4j日志记录框架非常相似。

Python记录范例 (Python Logging Example)

Let’s look at different ways we can use python logging module to log messages.

让我们看看可以使用python日志记录模块记录消息的不同方式。

简单记录示例 (Simple Logging Example)

The simplest form of logging occurs in form of only String messages. Let’s quickly look at an example code snippet:

最简单的日志记录形式只有字符串消息形式。 让我们快速看一下示例代码片段:

import logging

logging.warning("Warning log.")
logging.info("Info log.")

The output will be:

python logging example

输出将是:

Do you wonder why only the warning level log appeared in the console? This is because the default level of logging is WARNING.

您是否想知道为什么只有警告级别日志出现在控制台中? 这是因为默认的日志记录级别是WARNING

Python日志记录到文件 (Python logging to file)

Console logging is quite clear but what if we want to search through the logs after a day or a week? Won’t it be better if the logs were just collected at a single place where we can run simple text operations? Actually, we can log our messages to a file instead of a console.

控制台日志记录非常清楚,但是如果我们想在一天或一周后搜索日志,该怎么办? 如果仅将日志收集在一个我们可以运行简单文本操作的地方会更好吗? 实际上,我们可以将消息记录到文件而不是控制台中。

Let’s modify our script to do the necessary configuration:

让我们修改脚本以进行必要的配置:

import logging

# Configure file
logging.basicConfig(filename = 'my_logs.log', level = logging.DEBUG)

logging.warning("Warning log.")
logging.info("Info log.")
logging.debug("Debug log.")

When we run this script, we will not get back any output as all the logging is done in the file which is made by the script itself. Its content looks like:

当我们运行该脚本时,由于所有日志记录都在脚本本身创建的文件中完成,因此我们将不会获得任何输出。 其内容如下:

WARNING:root:Warning log.
INFO:root:Info log.
DEBUG:root:Debug log.

As we also used the log level as Debug, all the levels of logs are present in the file.

由于我们还将日志级别用作“调试”,因此所有级别的日志都存在于文件中。

不带附加内容的Python记录消息 (Python logging messages without append)

In our last example, we wrote a simple script to log messages in a file. Now, go on and run the same script again and again. You’ll notice that the file is appended with messages and new logs are added to last content. This is the default behavior of the logging module.

在最后一个示例中,我们编写了一个简单的脚本将消息记录在文件中。 现在,继续并一次又一次地运行相同的脚本。 您会注意到该文件附加了消息,并且新日志已添加到最后一个内容。 这是日志记录模块的默认行为。

To modify this so that the messages are included as a fresh file, make slight changes in the configuration as:

要对此进行修改,以使消息作为新文件包含在内,请对配置进行一些小的更改,如下所示:

import logging

# Configure file
logging.basicConfig(filename = 'my_logs.log', filemode='w', level = logging.DEBUG)

logging.warning("Warning log.")
logging.info("Info log.")
logging.debug("Debug log.")

We just added a new attribute as filemode. Now, run the script multiple times:

python logging to file

我们刚刚添加了一个新属性作为filemode 。 现在,多次运行脚本:

The content of the log file now looks like:

现在,日志文件的内容如下所示:

WARNING:root:Warning log.
INFO:root:Info log.
DEBUG:root:Debug log.

So, the messages are present as only fresh messages.

因此,消息仅作为新消息出现。

Python记录格式 (Python Logging Format)

Of course, the format of current logs is, strange! We will try to clean our messages and put some formatting. Fortunately, it is just a matter of a single line configuration. Let’s quickly look at python logging format example:

当然,当前日志的格式很奇怪! 我们将尝试清除消息并放入一些格式。 幸运的是,这只是单线配置的问题。 让我们快速看一下python日志记录格式示例:

import logging

# Configure file
logging.basicConfig(filename='my_logs.log', filemode='w',
                    format='%(levelname)s: %(message)s', level=logging.DEBUG)

logging.warning("Warning log.")
logging.info("Info log.")
logging.debug("Debug log.")

Now in this case, the content of the log file looks like:

现在,在这种情况下,日志文件的内容如下所示:

WARNING: Warning log.
INFO: Info log.
DEBUG: Debug log.

Much cleaner, right?

清洁得多吧?

日期时间的Python日志记录配置 (Python logging configurations for date time)

The log messages would make a lot of sense in real scenarios when we know when did an event actually occurred! We will try to provide date and timestamp to our messages. Again, it is just a matter of a single line configuration. Let’s quickly look at an example code snippet:

当我们知道事件实际发生的时间时,在实际情况下,日志消息会很有用! 我们将尝试为我们的消息提供日期和时间戳。 同样,这只是单线配置的问题。 让我们快速看一下示例代码片段:

import logging

# Configure file
logging.basicConfig(filename='my_logs.log', filemode='w',
                    format='%(levelname)s -> %(asctime)s: %(message)s', level=logging.DEBUG)

logging.warning("Warning log.")
logging.info("Info log.")
logging.debug("Debug log.")

We only added a single attribute as asctime. Now in this case, the content of the log file looks like:

我们只添加了一个属性asctime 。 现在,在这种情况下,日志文件的内容如下所示:

WARNING -> 2017-12-09 12:56:25,069: Warning log.
INFO -> 2017-12-09 12:56:25,069: Info log.
DEBUG -> 2017-12-09 12:56:25,069: Debug log.

Making much more sense now.

现在变得更加有意义。

Python记录getLogger() (Python logging getLogger())

Now, we were making a direct use of logging module. Why not just get an object and use it to log messages. Let’s quickly look at an example code snippet:

现在,我们直接使用了日志记录模块。 为什么不只是获取一个对象并使用它来记录消息。 让我们快速看一下示例代码片段:

import logging

# Configure file
logging.basicConfig(filename='my_logs.log', filemode='w',
                    format='%(levelname)s -> %(asctime)s: %(message)s', level=logging.DEBUG)
logger = logging.getLogger(__name__)

logger.info("Using custom logger.")
shubham = {'name': 'Shubham', 'roll': 123}
logger.debug("Shubham: %s", shubham)

We only added a call to getLogger. Now in this case, the content of the log file looks like:

我们只添加了对getLogger的调用。 现在,在这种情况下,日志文件的内容如下所示:

INFO -> 2017-12-09 13:14:50,276: Using custom logger.
DEBUG -> 2017-12-09 13:14:50,276: Shubham: {'name': 'Shubham', 'roll': 123}

Clearly, we can log variables values as well. This will help including much more information in log messages about current state of the program.

显然,我们也可以记录变量值。 这将有助于在日志消息中包含有关程序当前状态的更多信息。

Python日志记录配置文件 (Python logging config file)

Now, it is a tedious process to provide same logging information in multiple files. What we can do is, we can centralise our configuration into a single place so that whenever we need to make any change, it is needed at a single place only.

现在,在多个文件中提供相同的日志记录信息是一个繁琐的过程。 我们可以做的是,我们可以将配置集中到一个地方,这样,无论何时需要进行任何更改,都只需在一个地方进行。

We can do this by creating a config file as shown:

我们可以通过创建一个配置文件来做到这一点,如下所示:

[loggers]
keys=root,JournalDev
 
[handlers]
keys=fileHandler, consoleHandler
 
[formatters]
keys=myFormatter
 
[logger_root]
level=CRITICAL
handlers=consoleHandler
 
[logger_JournalDev]
level=INFO
handlers=fileHandler
qualname=JournalDev
 
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=myFormatter
args=(sys.stdout,)
 
[handler_fileHandler]
class=FileHandler
formatter=myFormatter
args=("external_file.log",)
 
[formatter_myFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

This way, we configured root and a JournalDev logger, provided a logger to both of these along with Handlers and a format. Now, we can make use of this logger file in our script:

这样,我们配置了root和JournalDev记录器,为这两个记录器以及Handlers和格式提供了记录器。 现在,我们可以在脚本中使用此记录器文件:

import logging
import logging.config

logging.config.fileConfig('logging.conf')
logger = logging.getLogger("JournalDev")

logger.info("Custom logging started.")
logger.info("Complete!")

As we configured two loggers in the file, we will see this output on the console as well:

python logging configuration file

当我们在文件中配置了两个记录器时,我们还将在控制台上看到以下输出:

These logs will be present in a file named external_file.log as well:

这些日志也将出现在名为external_file.log的文件中:

2017-12-09 13:52:49,889 - JournalDev - INFO - Custom logging started.
2017-12-09 13:52:49,889 - JournalDev - INFO - Complete!

This way, we can keep the logging configuration completely separate.

这样,我们可以使日志记录配置完全独立。

In this lesson, we learned about various functions provided by python logging module and saw how they work.

在本课程中,我们学习了python日志记录模块提供的各种功能,并了解了它们如何工作。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/17431/python-logging

python日志记录

Python实用教学】Python 中如何高效完美地处理日志记录 优雅地处理日志对于应用程序的健康运行至关重要。logging模块为开发者提供了多种方法来记录和管理日志信息。从基础的配置到高级的处理器和过滤器,在本文中全面探讨了 Python 中如何优雅地处理日志。 阅读详情

相关推荐

Python Django日志记录解析

在 Django 中,日志记录是一项强大的工具,允许开发者记录应用程序运行过程中发生的信息,以便更轻松地调试、监控和维护系统。Django 的日志系统基于 Python 的标准库模块 logging 提供的功能,并支持高度自定义的日志配置。

1085

记录Python脚本的运行日志的方法

主要介绍了记录Python脚本的运行日志的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

Python中的日志记录与调试技巧

模块记录程序的正常运行信息外,我们还可以利用日志进行调试。通过在程序中插入日志语句,我们可以方便地查看关键代码的执行情况、变量的值以及函数调用等信息。:ipdb是一个基于pdb和IPython的调试器,结合了pdb的调试功能和IPython的交互式特性。通过在代码中设置断点,我们可以逐步执行程序,查看变量的值,以及调用栈等信息。:pdbpp是Python内置调试器pdb的一个增强版本,提供了更多的功能和更好的用户体验。除了Python内置的调试工具外,还有一些第三方的库和工具可以帮助我们更高效地进行调试。

weixin_71166183的博客 1393

Python日志记录

Python日志记录

OnlyLove_的博客 2539

如何在 Python 中更优雅地记录日志

日志记录是软件开发中不可或缺的一部分,可以帮助开发人员在应用程序运行过程中跟踪问题、调试代码和监控系统状态。在Python中,有多种方式可以记录日志。本篇博客将介绍一些优雅的日志记录最佳实践,帮助您在Python应用程序中实现可维护、可扩展和易于调试的日志记录

hj1993的博客 2948

Python实现日志的记录

日志等级从低到高的顺序是: DEBUG < INFO < WARNING < ERROR < CRITICAL。:记录Web服务器的活动,如访问者的IP地址、请求的资源、HTTP状态代码等。:记录与安全相关的事件,如登录尝试、权限更改、防火墙活动等。:记录操作系统、应用程序、硬件组件等的事件和错误。:记录特定应用程序的运行状态、用户活动、异常等。:记录数据库的更改、查询、事务等。,它将是我持续更新的巨大动力,】如果对您有所帮助,欢迎。

Oblning的博客 3043

python记录日志_python日志记录教程

python记录日志Logging is a very important functionality for a programmer. For both debugging and displaying run-time information, logging is equally useful. In this article, I will present why and how you...

weixin_26741235的博客 1334

Python 日志记录

典型的日志记录的步骤是这样的: 创建logger 创建handler 定义formatter 给handler添加formatter 给logger添加handler logger可以看做是一个记录日志的人,对于记录的每个日志,他需要有一套规则,比如记录的格式(formatter),等级(level)等等,这个规则就是handler。使用logger.addHandler(handler)添加多个规则,就可以让一个logger记录多个日志。 1 import logging 2 3 # 1、创建

weixin_48633625的博客 299

python日志记录

python日志记录 文章目录python日志记录一、简介二、内容2.1 日志级别2.2 handler日志输出地2.3 formatter日志格式2.4 filter过滤器三、示例3.1 配置文件logging.json3.2 代码示例 一、简介 这里介绍在python中的日志记录,流程逻辑与java中类似。日志记录包含Logger(日志记录器)、Handler(日志输出地)、 Filter...

panda-star的博客 587

Loguru - Python 日志记录

此外,这个库旨在通过添加一堆有用的功能来解决标准记录器的警告,从而减少Python日志记录的痛苦。尽管日志对性能的影响在大多数情况下可以忽略不计,但零成本记录器将允许在任何地方使用它而无需担心。记录代码中出现的异常对于跟踪错误很重要,但是如果你不知道为什么它失败了,那就没用了。如果您需要旋转记录器,如果您想删除旧日志,或者如果您希望在关闭时压缩文件,它也。在即将发布的版本中,Loguru的关键功能将在C中实现以获得最大速度。我做了,但日志记录是每个应用程序的基础,并简化了调试过程。

AI工程化、开源分享、文档翻译、代码笔记 1691

python模块 — 日志记录模块logging

logging是Python内置的日志记录模块,用于在程序中实现灵活的日志功能。使用logging模块可以记录错误、异常、警告和其他关键信息,以便于诊断和调试应用程序。logging模块提供了以下主要组件:1. Logger(日志器):用于创建或获取一个用于发送日志记录消息的Logger对象。我们可以在不同的模块中定义和使用Logger对象来记录日志。2. Handler(处理器):用于指定将如何处理和输出日志消息。Handler可以将日志消息写入文件、控制台、网络等不同的目标。

个人博客 4105

python日志记录

日志轮转 —Linux logrotate服务,—配置文件:/etc/logrotate.conf或者/etc/logrotate.d。生成logger对象的时候,没有传递参数进去,那就是root logger—父日志。如果传递传递了参数进去,类似于子logger。格式器 Formatter。子日志器会继承父日志的配置。处理器 Handler。日志器 Logger。过滤器 Filter。...

Ernestjackson的博客 1152

python Logging日志记录模块详解

写在篇前   logging是Python的一个标准库,其中定义的函数和类为应用程序和库的开发实现了一个灵活的事件日志系统。Python logging 的配置由四个部分组成:Logger、Handlers、Filter、Formatter。本篇博客将依次介绍这四个主要部分以及logging的基本应用。   在开始之前,我们有必要先了解一下,什么时候我们才有必要使用logging模块,什么时候抛出...

jeffery0207的博客 1万+

chatgpt赋能pythonPython中的日志记录

日志记录是指记录应用程序运行时发生的事件和错误的过程。这些事件和错误可以是程序在运行时的任何行为,例如用户行为、系统事件、数据处理等。日志记录可以帮助我们更好地理解应用程序的运行方式,检测错误和故障,并改进应用程序的性能。本文由chatgpt生成,文章没有在chatgpt生成的基础上进行任何的修改。以上只是chatgpt能力的冰山一角。作为通用的Aigc大模型,只是展现它原本的实力。对于颠覆工作方式的ChatGPT,应该选择拥抱而不是抗拒,未来属于“会用”AI的人。

b45e1933f46的博客 207

[编程基础] Python日志记录库logging总结

Python日志记录教程展示了如何使用日志记录模块在Python中进行日志记录。 文章目录1 介绍1.1 背景1.2 Python日志记录模块1.3 根记录器2 Python logging模块使用教程2.1 Python logging模块简单使用2.2 Python有效日志记录级别2.3 Python有效日志记录级别2.4 Python记录处理程序2.5 Python记录格式化程序2.6 Python日志基本配置2.7 Python日志记录文件配置2.8 Python日志记录变量2.9 Python日志

You and Me 1237

Python实现的日志记录类实例

在软件开发和系统维护过程中,日志记录是一项非常重要的任务。在Python中,我们可以使用日志模块来实现灵活和可配置的日志记录功能。本文将介绍如何使用Python实现一个实用的日志记录类。通过使用这个简单而实简单而实用的而实用的日志记录类,我们可以轻松地在Python应用程序中实现灵活和可配置的日志记录功能。我们可以创建一个实例,并使用不同的方法记录不同级别的日志。类的实例,并使用不同的方法记录了不同级别的日志。,该格式包含了日志记录的时间、日志级别和消息内容。,这意味着所有级别的日志记录都会被记录下来。

DevForge的博客 193

Python 日志记录:6大日志记录库的比较

日志记录框架是一种工具,可帮助您标准化应用程序中的日志记录过程。虽然某些编程语言提供内置日志记录模块作为其标准库的一部分,但大多数日志记录框架都是第三方库,例如logging(Python)、Log4j(Java)、Zerolog(Go) 或Winston(Node.js)。有时,组织会选择开发自定义日志记录解决方案,但这通常仅限于具有高度专业化需求的大型公司。虽然 Python 在其标准库中提供了强大且功能丰富的日志记录解决方案,但第三方日志记录生态系统也提供了一系列引人注目的替代方案。

Null的博客 2万+

10个Python日志记录最佳实践

Python编程世界里,日志就像是程序员的“侦探笔记”,记录着程序运行过程中的关键信息,帮助我们在调试、监控、故障排查等场景下快速定位问题。Python内置的logging模块提供了强大且灵活的日志记录功能,让你轻松驾驭这个强大的工具。本文将通过十个最佳实践,带你全面掌握logging模块的配置与应用技巧。通过以上十个实践,你应该已经掌握了Pythonlogging。

wenjie20070212的博客 1304
上一篇: sql in not in_SQL IN – SQL NOT IN
下一篇: kotlin_Kotlin
cunchi4221
博客等级 码龄10年 643粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值