python记录日志

Making your code production-ready is not an easy task. There are so many things to consider, one of them being able to monitor the application’s flow. That’s where logging comes in — a simple tool to save some nerves and many, many hours.

使您的代码可用于生产环境并非易事。 有很多事情要考虑,其中之一就是能够监视应用程序的流程。 这就是日志记录的来源-一个简单的工具,可以节省很多时间和许多时间。

Python has great built-in support for logging. It’s implemented through the logging library, and is quite similar to options found in other major programming languages.

Python具有强大的内置日志记录支持。 它是通过logging库实现的,与其他主要编程语言中的选项非常相似。

If you’re more of a video person, or just want to reinforce your knowledge, feel free to watch our video on the topic.

如果您更喜欢视频,或者只是想增强自己的知识,请随时观看我们有关该主题的视频。

Before we jump into the code, let’s briefly discuss why you should care about logging, and cover some light theory behind it.

在进入代码之前,让我们简要讨论一下为什么您应该关心日志记录,并介绍其背后的一些轻理论。

记录-为什么? (Logging — Why?)

I’ve mentioned previously that logging is used to monitor applications flow, among other things. The question you may have now is why can’t we just use print statements? We can, but it’s not ideal. There’s no way to track the severity of the message through simple print statements. That’s where logging shines.

前面已经提到过,日志记录用于监视应用程序流,等等。 您现在可能遇到的问题是, 为什么我们不能仅使用打印语句? 我们可以,但是并不理想。 无法通过简单的打印语句来跟踪消息的严重性。 那就是伐木大放异彩的地方。

Here’s my top 3 list of reasons why you should use logging in your applications:

这是我应该在应用程序中使用日志记录的前三点原因:

  1. To get an understanding of how your code works — you don’t want to be blind in production

    为了了解您的代码如何工作 -您不想在生产中盲目

  2. To capture and fix unexpected errors — and detect potential bigger issues with your code

    捕获和修复意外错误 -并检测代码中潜在的更大问题

  3. To analyze and visualize how the app performs — more advanced topic

    分析和可视化应用程序的性能 -更高级的主题

As mentioned previously, the logging library is built into Python programming language and provides 5 severity levels:

如前所述, logging库内置于Python编程语言中,并提供5个严重级别:

  • DEBUG
    调试
  • INFO
    信息
  • WARNING
    警告
  • ERROR
    错误
  • CRITICAL
    危急

You can reason just from the name when you should use one instead of the other, but it’s important to note that Python shows messages of severity level WARNING and above by default. That behavior can be changed.

您可以仅从名称中推断出何时应使用一个而不是另一个,但要注意的是,Python默认显示严重级别为WARNING或更高的消息。 该行为可以更改。

Let’s now explore logging with some simple code.

现在让我们用一些简单的代码来探索日志记录。

记录-如何? (Logging — How?)

To start, let’s perform a couple of imports:

首先,让我们执行几个导入:

import randomimport timefrom datetime import datetimeimport logging

As you can see, the logging library is included here. I’ve mentioned previously that Python will show only messages of severity level WARNING and above, so here’s how we can change that:

如您所见, logging库包含在此处。 前面已经提到过,Python将仅显示严重级别为WARNING及以上的消息,因此,我们可以通过以下方法进行更改:

logging.basicConfig(level=logging.DEBUG)

And that’s it! Let's declare a simple function that generates a random number from 0 to 4, and logs messages of different severity level based on that random number. After a message is displayed, the program sleeps for a second. This function is used purely for testing:

就是这样! 让我们声明一个简单的函数,该函数生成一个0到4之间的随机数,并根据该随机数记录不同严重性级别的消息。 显示一条消息后,程序将Hibernate一秒钟。 此功能仅用于测试:

def log_tester():    x = random.randint(0, 4)    if x == 0:        logging.debug(‘Debug message’)    elif x == 1:        logging.info(‘Info message’)    elif x == 2:        logging.warning(‘Warning message’)    elif x == 3:        logging.error(‘Error message’)    elif x == 4:        logging.critical(‘Critical message’)    time.sleep(1)    return

And finally, we need to call this function somewhere, so why don’t we do that in a loop? Just to have multiple messages printed out:

最后,我们需要在某个地方调用此函数,那么为什么不循环执行呢? 只是为了打印出多条消息:

for i in range(5):    log_tester()

If you run this code now, you will get an output similar to mine:

如果现在运行此代码,您将获得类似于我的输出:

Output:WARNING:root:Warning messageERROR:root:Error messageDEBUG:root:Debug messageINFO:root:Info messageINFO:root:Info message

Keep in mind that your output may differ, due to the randomization process.

请记住,由于随机化过程,您的输出可能会有所不同。

This format is fine for some cases, but other times we might want more control, and to be able to further customize how the output looks like.

在某些情况下,这种格式是可以的,但在其他情况下,我们可能需要更多控制权,并能够进一步自定义输出的外观。

Let’s explore how.

让我们探讨一下。

输出格式 (Output formatting)

Let’s alter the logging.basicConfig slightly:

让我们稍微修改logging.basicConfig

logging.basicConfig(level=logging.DEBUG, format=’%(levelname)s → %(name)s:%(message)s’)

If you were to run this code now, the messages would be formatted in the way specified:

如果您现在要运行此代码,则将以指定的方式格式化消息:

Output:CRITICAL → root:Critical messageWARNING → root:Warning messageDEBUG → root:Debug messageDEBUG → root:Debug messageCRITICAL → root:Critical message

That’s fine, but what I like to do is to add current date and time information to messages. It’s easy to do with format strings:

很好,但是我想做的是向消息中添加当前日期和时间信息。 使用格式字符串很容易:

logging.basicConfig(level=logging.DEBUG, format=f’%(levelname)s → {datetime.now()} → %(name)s:%(message)s’)

Here’s how our new format looks like:

我们的新格式如下所示:

DEBUG → 2020–08–09 10:32:11.519365 → root:Debug messageDEBUG → 2020–08–09 10:32:11.519365 → root:Debug messageDEBUG → 2020–08–09 10:32:11.519365 → root:Debug messageERROR → 2020–08–09 10:32:11.519365 → root:Error messageWARNING → 2020–08–09 10:32:11.519365 → root:Warning message

Now we’re getting somewhere! To get the actual time the message was logged you’d need to embed the call to datetime.now() inside the message.

现在我们到了某个地方! 要获取记录消息的实际时间,您需要将调用嵌入到消息中的datetime.now()

The only problem is that the logs are lost forever once the terminal window is closed. So instead of outputting the messages to the console, let’s explore how we can save them to a file.

唯一的问题是,一旦关闭终端窗口,日志将永远丢失。 因此,让我们探索如何将它们保存到文件中,而不是将消息输出到控制台。

保存到文件 (Saving to a file)

To save log messages to a file, we need to specify values for two more parameters:

要将日志消息保存到文件,我们需要为另外两个参数指定值:

  • filename — name of the file in which logs will be saved

    filename将在其中保存日志的文件的名称

  • filemode — write or append modes, we’ll explore those in a bit

    filemode写入或追加模式,我们将在稍后进行探讨

Let’s see how we can use the write mode first. This mode will overwrite any existing file with the specified name every time the application is run. Here’s the configuration:

让我们看看如何首先使用write模式。 每次运行该应用程序时,此模式都会覆盖具有指定名称的任何现有文件。 配置如下:

logging.basicConfig(    filename=’test.log’,    filemode=’w’,    level=logging.DEBUG,    format=’%(levelname)s → {datetime.now()} → %(name)s:%(message)s’)

If you run the program now, no output would be shown in the console. Instead, a new file called test.log is created, and it contains your log messages:

如果立即运行该程序,则控制台中不会显示任何输出。 而是创建一个名为test.log的新文件,其中包含您的日志消息:

test.log:WARNING → 2020–08–09 10:35:54.115026 → root:Warning messageINFO → 2020–08–09 10:35:54.115026 → root:Info messageWARNING → 2020–08–09 10:35:54.115026 → root:Warning messageDEBUG → 2020–08–09 10:35:54.115026 → root:Debug messageCRITICAL → 2020–08–09 10:35:54.115026 → root:Critical message

If you were to run the program again, these 5 rows would be lost and replaced with new 5 rows. In some cases that’s not what you want, so we can use the append mode to keep the previous data and write new rows o the end. Here’s the configuration:

如果要再次运行该程序,这5行将丢失并被新的5行替换。 在某些情况下,这不是您想要的,因此我们可以使用append模式保留先前的数据并在末尾写入新行。 配置如下:

logging.basicConfig(    filename=’test.log’,    filemode=’a’,    level=logging.DEBUG,    format=’%(levelname)s → {datetime.now()} → %(name)s:%(message)s’)

If you were to run the program now, and look at our file, you’d see 10 rows there:

如果您现在要运行该程序并查看我们的文件,则会在其中看到10行:

test.log:WARNING → 2020–08–09 10:35:54.115026 → root:Warning messageINFO → 2020–08–09 10:35:54.115026 → root:Info messageWARNING → 2020–08–09 10:35:54.115026 → root:Warning messageDEBUG → 2020–08–09 10:35:54.115026 → root:Debug messageCRITICAL → 2020–08–09 10:35:54.115026 → root:Critical messageDEBUG → 2020-08-09 10:36:24.699579 → root:Debug messageINFO → 2020-08-09 10:36:24.699579 → root:Info messageCRITICAL → 2020-08-09 10:36:24.699579 → root:Critical messageCRITICAL → 2020-08-09 10:36:24.699579 → root:Critical messageCRITICAL → 2020-08-09 10:36:24.699579 → root:Critical message

And that’s it. You now know the basics of logging. Let’s wrap things up in the next section.

就是这样。 您现在知道了日志记录的基础知识。 让我们在下一节中总结一下。

你走之前 (Before you go)

Logging isn’t the most fun thing to do, sure. But without it, you are basically blind. Take a moment to think about how would you monitor the behavior and flow of a deployed application without logging? Not so easy, I know.

当然,记录并不是最有趣的事情。 但是没有它,您基本上是盲人。 花点时间考虑一下如何在不登录的情况下监视已部署应用程序的行为和流程? 我知道这并不容易。

In 5 minutes we’ve got the basics covered, and you are now ready to implement logging in your next application. It doesn’t have to be an application in strict terms, you can also use it for data science projects as well.

在5分钟内,我们已经涵盖了基础知识,现在您可以在下一个应用程序中实现日志记录了。 严格来说,它不一定是应用程序,也可以将其用于数据科学项目。

Thanks for reading. Take care.

谢谢阅读。 照顾自己。

Join my private email list for more helpful insights.

加入我的私人电子邮件列表以获取更多有用的见解。

翻译自: https://towardsdatascience.com/logging-explained-in-5-minutes-walkthrough-with-python-8bd7d8c2cf3a

python记录日志

http://www.taodudu.cc/news/show-994810.html

相关文章:

  • p值 t值 统计_非统计师的P值
  • 如何不部署Keras / TensorFlow模型
  • 对食材的敬畏之心极致产品_这些数据科学产品组合将给您带来敬畏和启发(2020年中的版本)
  • 向量积判断优劣弧_判断经验论文优劣的10条诫命
  • sql如何处理null值_如何正确处理SQL中的NULL值
  • 数据可视化 信息可视化_动机可视化
  • 快速数据库框架_快速学习新的数据科学概念的框架
  • 停止使用p = 0.05
  • 成像数据更好的展示_为什么更多的数据并不总是更好
  • vue domo网站_DOMO与Tableau-逐轮
  • 每个人都应该使用的Python 3中被忽略的3个功能
  • 数据探查_数据科学家,开始使用探查器
  • 从ncbi下载数据_如何从NCBI下载所有细菌组件
  • 线性插值插值_揭秘插值搜索
  • 如果您不将Docker用于数据科学项目,那么您将生活在1985年
  • docker部署flask_使用Docker,GCP Cloud Run和Flask部署Scikit-Learn NLP模型
  • 问卷 假设检验 t检验_真实问题的假设检验
  • 大数据技术 学习之旅_为什么聚焦是您数据科学之旅的关键
  • 无监督学习 k-means_无监督学习-第4部分
  • 深度学习算法原理_用于对象检测的深度学习算法的基本原理
  • 软件本地化 pdf_软件本地化与标准翻译
  • 数据库不停机导数据方案_如何计算数据停机成本
  • python初学者_面向初学者的20种重要的Python技巧
  • 贝叶斯网络建模
  • 数据科学家数据分析师_使您的分析师和数据科学家在数据处理方面保持一致
  • python db2查询_如何将DB2查询转换为python脚本
  • 爱因斯坦提出的逻辑性问题_提出正确问题的重要性
  • 餐厅数据分析报告_如何使用数据科学选择理想的餐厅设计场所
  • 熊猫直播 使用什么sdk_没什么可花的-但是16项基本操作才能让您开始使用熊猫
  • 关系型数据库的核心单元是_核中的数据关系

python记录日志_5分钟内解释日志记录—使用Python演练相关推荐

  1. ip访问次数统计 nginx_分析Nginx 5分钟内的 日志 然后统计出 访问次数最多的ip 地址 和次数...

    #!/bin/bash #author: linuxhub.org #取出nginx五分钟内的日志 #Nginx日志格式: #if [ -z $1 ];then #echo "请在脚本后面加 ...

  2. 《Python编程从入门到实践》记录之Python函数返回值

    目录 1.返回简单值 2.返回字典 3.结合使用函数和while循环 更多关于Python函数的知识见如下博文: <Python编程从入门到实践>记录之Python函数定义.使用 < ...

  3. 服务器日志记录_5种改善服务器日志记录的技术

    服务器日志记录 在最近的时间里,我们已经看到了许多工具可以帮助您理解日志. 开源项目(例如Scribe和LogStash),内部部署工具(例如Splunk)以及托管服务(例如SumoLogic和Pap ...

  4. html表头解释_1分钟内解释的html

    html表头解释 Before I explain HTML I want to begin by restating a couple of points I made in a previous ...

  5. html5 学习_5分钟内学习HTML

    html5 学习 by Eric Tirado 埃里克·蒂拉多(Eric Tirado) 5分钟内学习HTML (Learn HTML in 5 minutes) 快速教程可帮助您开始构建网站. (A ...

  6. 用python做预测模型的好处_如何用Python在10分钟内建立一个预测模型

    匿名用户 1级 2017-01-01 回答 预测模型的分解过程 我总是集中于投入有质量的时间在建模的初始阶段,比如,假设生成.头脑风暴.讨论或理解可能的结果范围.所有这些活动都有助于我解决问题,并最终 ...

  7. python hook_五分钟内用Python实现GitHook

    githooks.png Githook 也称 Git 钩子,是在 Git 仓库中特定事件发生时自动运行的脚本.它可以让你自定义 Git 内部的行为,在开发周期中的关键点出发自定义行为. Git Ho ...

  8. css flexbox模型_5分钟内学习CSS Flexbox-初学者教程

    css flexbox模型 快速介绍流行的布局模块 (A quick introduction to the popular layout module) In this post, you'll l ...

  9. ppt python 图表_5分钟python:在PPT里做三联柱形图

    分钟说长不长,说短不短,可以学会对办公自动化的诀窍.在这个python的PPT专辑里,会教大家如何用python自动化一步步,一行行程序,手把手的编码说明,生成好看的PPT. 接上节的简单柱形图生成, ...

最新文章

  1. curl模拟多线程抓取网页(优化)
  2. js进阶 9-14 js如何实现下拉列表多选移除
  3. VTK:PolyData之ColorCells
  4. 利用IDisposable接口构建包含非托管资源对象
  5. Android 布局 优先显示右侧的控件
  6. (组合数学笔记)Pólya计数理论_Part.10_Pólya定理的推广——De Bruijn定理的母函数形式
  7. 挂了三次科目二的我,竟被一台智能车征服 | 威马W6停车挑战
  8. 多项目结构_[网红项目]碳云大厦
  9. .NET2.0中,Winform程序如何异步调用Web Service呢?[Demo下载]——与.net1.1环境下比较...
  10. weblogic安装升级配置
  11. c语言中x的n次方怎么表示_为什么一定要慎用C语言标准库中的pow函数,你知道吗?...
  12. Python实例练手项目源码 - 关不掉的窗口
  13. labview 控件安装步骤
  14. 计算机主要应用是什么意思,admin是什么意思 Admin的用途介绍
  15. Openbravo开发手册
  16. 小牛叔讲Python第11章:函数的高级用法以及匿名函数
  17. 前端批量打包下载图片_个人总结 _@jie
  18. 牛逼哄哄的对象深复制
  19. 上传word文档显示服务器出错,打开office出错的几种解决方法
  20. uml sequence diagram

热门文章

  1. 贪心算法——选择不相交区间问题
  2. java环境变量的配置与详解,这些知识你必须拿下
  3. web开发要学多久,HTML表格标签,薪资翻倍
  4. linux epoll机制对TCP 客户端和服务端的监听C代码通用框架实现
  5. 关于web前端的学习路线
  6. 2.x最终照着教程,成功使用OpenGL ES 绘制纹理贴图,添加了灰度图
  7. 公共的Controler,是给非授权的用户访问
  8. 机器学习算法及应用领域相关的中国大牛
  9. DirectXInput
  10. 1.初学MVC3学习笔记1