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 logginglogging.warning("Warning log.")
logging.info("Info log.")

The output will be:

输出将是:

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:

我们刚刚添加了一个新属性作为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.configlogging.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:

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

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日志记录相关推荐

  1. python log模块_Python日志模块-logging

    一.logging模块 日志的作用可以简单总结为以下3点: 1.程序调试 2.了解软件程序运行情况,是否正常 3.软件程序运行故障分析与问题定位 1.日志的等级 不同的应用程序所定义的日志等级可能会有 ...

  2. python logging模块默认日志级别_Python 日志模块logging

    logging模块: logging是一个日志记录模块,可以记录我们日常的操作. logging日志文件写入默认是gbk编码格式的,所以在查看时需要使用gbk的解码方式打开. logging日志等级: ...

  3. python log模块_python日志模块logbook使用方法

    python自带了日志模块logging,可以用来记录程序运行过程中的日志信息.同时python还有logbook模块用来取代logging模块,在很多的项目中logbook模块使用也是比较的多,因此 ...

  4. python 打印模块_Python 日志打印模块

    1 logging模块简介 logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级.日志保存路径.日志文件回滚等:相比print,具备如下优点: 可以通过设置不同 ...

  5. python log日志级别_python – 日志记录:如何为处理程序设置最大日志级别

    您可以向文件处理程序添加过滤器.这样,您可以将特定级别重定向到不同的文件. import logging class LevelFilter(logging.Filter): def __init__ ...

  6. es获取最大时间的记录_Python日志写入ES之五种方案比较

    ​实时/准实时方案可以使用以下四种方式实现: flume+kafka+spark准实时写入ES logging + CMRESHandler实时写入ES 利用python中的Elasticsearch ...

  7. python清理日志脚本_Python日志:如果在程序运行时删除了日志文件,则创建新的日志文件(RotatingFileHandler)...

    我有一个python程序在运行,它使用timedrotingfilehandler连续记录到一个文件.有时我想在不关闭程序的情况下获取日志文件,所以我只需将日志文件剪切并粘贴到不同的位置.在 程序不会 ...

  8. python多线程并发_Python进阶记录之基础篇(二十四)

    回顾 在Python进阶记录之基础篇(二十三)中,我们介绍了进程的基本概念以及Python中多进程的基本使用方法.其中,需要重点掌握多进程的创建方法.进程池和进程间的通信.今天我们讲一下Python中 ...

  9. python生成日志文件_Python 日志生成器

    需求分析 网站日志需求分析 由于缺乏真实网站日志,在这里用 Python 2.7.5 构建日志生成器模拟网站日志,作为之后实验的基础. 之后的实验为用 Flume 采集网站的日志信息,基于此做一系列的 ...

最新文章

  1. Control~Kalman filter
  2. java engine_java使用OGEngine开发2048
  3. visual basic.net 2019-当前内存状态、字符串内插、操作系统系统信息
  4. 狂妄之人怎么用计算机弹,【B】 Undertale Sans战斗曲 MEGALOVANIA狂妄之人
  5. 在大厂工作5年的大神,给前端初学者的四大建议,收藏咯
  6. 参加第六届中国制造业MES应用年会
  7. 【课本】【No.4】数字特征 离散/连续均值/方差 随机向量 协方差 相关系数 矩 偏度 峰度 多维均值/协方差 运算性质 条件期望 随机个随机向量的和 正态中的条件期望是线性函数
  8. react里 MD5加密
  9. ConstraintLayout约束控件详解
  10. Python单元测试报告框架PyTestReport
  11. 2022电大国家开放大学网上形考任务-简明中国古代史(山东)非免费(非答案)
  12. IIS无法启动:存储空间不足解决办法
  13. 传感器的使用(一)-火焰传感器
  14. prusai3打印机使用教程_【打印虎原创】Prusa_i3_3D打印机校准图解教程-基础篇
  15. DPDK内存管理总结
  16. Windows自带录屏
  17. Idea新建项目名后出现中括号别名
  18. python根据表格数据生成折线图_python生成折线图
  19. 旧路由器改装无线打印服务器,旧路由器改wifi放大器详细教程【图】
  20. 管理大规模容器集群能力包括_阿里巴巴大规模神龙裸金属 Kubernetes 集群运维实践...

热门文章

  1. leetcode解题笔记-Summary Ranges
  2. [转] 解决windows下eclipse中android项目关联android library project失败问题
  3. 采样干扰十大滤波算法程序大全
  4. System.IO.Directory.Delete 方法的使用
  5. [转载] python中sort,sorted,reverse,reversed的区别
  6. [转载] Python字符串常用操作命令
  7. [转载] PYTHON 网络编程
  8. Eclipse编译时函数报错:Undefined reference to 'pthread_create'
  9. 鸿蒙2.0手机版体验,华为鸿蒙OS 2.0手机版功能抢先曝光:体验前所未有
  10. Linux+gcc设置断点,gcc/g++常用编译选项和gdb常用调试命令