简体   繁体   English

Python 中的常用日志记录模块

[英]Common logging module in Python

I am new to python and just trying to learn and find better ways to write code.我是 Python 新手,只是想学习并找到更好的编写代码的方法。 I want to create a custom class for logging and use package logging inside it.我想创建一个用于日志记录的自定义类并在其中使用包日志记录。 I want the function in this class to be reusable and do my logging from other scripts rather than writing custom code in each and every scripts.我希望这个类中的函数是可重用的,并从其他脚本中进行日志记录,而不是在每个脚本中编写自定义代码。 Is there a good link you guys can share?大家有什么好的链接可以分享吗? Is this the right way to handle logging?这是处理日志记录的正确方法吗? I just want to avoid writing the same code in every script if I can reuse it from one module.如果我可以从一个模块中重用它,我只想避免在每个脚本中编写相同的代码。 I would highly appreciate any reply.我将不胜感激任何答复。

You can build a custom class that utilizes the built in python logging library.您可以构建一个利用内置 python日志库的自定义类。 There isn't really any right way to handle logging as the library allows you to use 5 standard levels indicating the severity of events ( DEBUG , INFO , WARNING , ERROR , and CRITICAL ).没有任何正确的方法来处理日志记录,因为该库允许您使用 5 个标准级别来指示事件的严重性( DEBUGINFOWARNINGERRORCRITICAL )。 The way you use these levels are application specific.您使用这些级别的方式是特定于应用程序的。 Here's another good explanation of the package.是对包另一个很好的解释。

It's indeed a good idea to keep all your logging configuration (formatters, level, handlers) in one place.将所有日志配置(格式化程序、级别、处理程序)放在一个地方确实是个好主意。

  • create a class wrapping a custom logger with your configuration创建一个用您的配置包装自定义记录器的类

  • expose methods for logging with different levels公开不同级别的日志记录方法

  • import this class wherever you want在任何你想要的地方导入这个类

  • create an instance of this class to log where you want创建此类的实例以记录您想要的位置

To make sure all you custom logging objects have the same config, you should make logging class own the configuration.为了确保所有自定义日志对象具有相同的配置,您应该让日志类拥有配置。

I don't think there's any links I can share for the whole thing but you can find links for the individual details I mentioned easily enough.我不认为我可以分享整个事情的任何链接,但您可以轻松找到我提到的各个细节的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM