Home Backend Development Python Tutorial Python中使用logging模块打印log日志详解

Python中使用logging模块打印log日志详解

Jun 10, 2016 pm 03:16 PM
logging module python

学一门新技术或者新语言,我们都要首先学会如何去适应这们新技术,其中在适应过程中,我们必须得学习如何调试程序并打出相应的log信息来,正所谓“只要log打的好,没有bug解不了”,在我们熟知的一些信息技术中,log4xxx系列以及开发Android app时的android.util.Log包等等都是为了开发者更好的得到log信息服务的。在Python这门语言中,我们同样可以根据自己的程序需要打出log。

log信息不同于使用打桩法打印一定的标记信息,log可以根据程序需要而分出不同的log级别,比如info、debug、warn等等级别的信息,只要实时控制log级别开关就可以为开发人员提供更好的log信息,与log4xx类似,logger,handler和日志消息的调用可以有具体的日志级别(Level),只有在日志消息的级别大于logger和handler的设定的级别,才会显示。下面我就来谈谈我在Python中使用的logging模块一些方法。

logging模块介绍

Python的logging模块提供了通用的日志系统,熟练使用logging模块可以方便开发者开发第三方模块或者是自己的Python应用。同样这个模块提供不同的日志级别,并可以采用不同的方式记录日志,比如文件,HTTP、GET/POST,SMTP,Socket等,甚至可以自己实现具体的日志记录方式。下文我将主要介绍如何使用文件方式记录log。

logging模块包括logger,handler,filter,formatter这四个基本概念。

logger:提供日志接口,供应用代码使用。logger最长用的操作有两类:配置和发送日志消息。可以通过logging.getLogger(name)获取logger对象,如果不指定name则返回root对象,多次使用相同的name调用getLogger方法返回同一个logger对象。
handler:将日志记录(log record)发送到合适的目的地(destination),比如文件,socket等。一个logger对象可以通过addHandler方法添加0到多个handler,每个handler又可以定义不同日志级别,以实现日志分级过滤显示。
filter:提供一种优雅的方式决定一个日志记录是否发送到handler。
formatter:指定日志记录输出的具体格式。formatter的构造方法需要两个参数:消息的格式字符串和日期字符串,这两个参数都是可选的。

基本使用方法

一些小型的程序我们不需要构造太复杂的log系统,可以直接使用logging模块的basicConfig函数即可,代码如下:

复制代码 代码如下:

'''
Created on 2012-8-12
 
@author: walfred
@module: loggingmodule.BasicLogger
'''
import logging
 
log_file = "./basic_logger.log"
 
logging.basicConfig(filename = log_file, level = logging.DEBUG)
 
logging.debug("this is a debugmsg!")
logging.info("this is a infomsg!")
logging.warn("this is a warn msg!")
logging.error("this is a error msg!")
logging.critical("this is a critical msg!")

运行程序时我们就会在该文件的当前目录下发现basic_logger.log文件,查看basic_logger.log内容如下:

复制代码 代码如下:

INFO:root:this is a info msg!
DEBUG:root:this is a debug msg!
WARNING:root:this is a warn msg!
ERROR:root:this is a error msg!
CRITICAL:root:this is a critical msg!

需要说明的是我将level设定为DEBUG级别,所以log日志中只显示了包含该级别及该级别以上的log信息。信息级别依次是:notset、debug、info、warn、error、critical。如果在多个模块中使用这个配置的话,只需在主模块中配置即可,其他模块会有相同的使用效果。

较高级版本

上述的基础使用比较简单,没有显示出logging模块的厉害,适合小程序用,现在我介绍一个较高级版本的代码,我们需要依次设置logger、handler、formatter等配置。

复制代码 代码如下:

'''
Created on 2012-8-12
 
@author: walfred
@module: loggingmodule.NomalLogger
'''
import logging
 
log_file = "./nomal_logger.log"
log_level = logging.DEBUG
 
logger = logging.getLogger("loggingmodule.NomalLogger")
handler = logging.FileHandler(log_file)
formatter = logging.Formatter("[%(levelname)s][%(funcName)s][%(asctime)s]%(message)s")
 
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(log_level)
 
#test
logger.debug("this is a debug msg!")
logger.info("this is a info msg!")
logger.warn("this is a warn msg!")
logger.error("this is a error msg!")
logger.critical("this is a critical msg!")

这时我们查看当前目录的nomal_logger.log日志文件,如下:

复制代码 代码如下:

[DEBUG][][2012-08-12 17:43:59,295]this is a debug msg!
[INFO][][2012-08-12 17:43:59,295]this is a info msg!
[WARNING][][2012-08-12 17:43:59,295]this is a warn msg!
[ERROR][][2012-08-12 17:43:59,295]this is a error msg!
[CRITICAL][][2012-08-12 17:43:59,295]this is a critical msg!

这个对照前面介绍的logging模块,不难理解,下面的最终版本将会更加完整。

完善版本

这个最终版本我用singleton设计模式来写一个Logger类,代码如下:

复制代码 代码如下:

'''
Created on 2012-8-12
 
@author: walfred
@module: loggingmodule.FinalLogger
'''
 
import logging.handlers
 
class FinalLogger:
 
 logger = None
 
 levels = {"n" : logging.NOTSET,
  "d" : logging.DEBUG,
  "i" : logging.INFO,
  "w" : logging.WARN,
  "e" : logging.ERROR,
  "c" : logging.CRITICAL}
 
 log_level = "d"
 log_file = "final_logger.log"
 log_max_byte = 10 * 1024 * 1024;
 log_backup_count = 5
 
 @staticmethod
 def getLogger():
  if FinalLogger.logger is not None:
   return FinalLogger.logger
 
  FinalLogger.logger = logging.Logger("oggingmodule.FinalLogger")
  log_handler = logging.handlers.RotatingFileHandler(filename = FinalLogger.log_file,\
  maxBytes = FinalLogger.log_max_byte,\
  backupCount = FinalLogger.log_backup_count)
  log_fmt = logging.Formatter("[%(levelname)s][%(funcName)s][%(asctime)s]%(message)s")
  log_handler.setFormatter(log_fmt)
  FinalLogger.logger.addHandler(log_handler)
  FinalLogger.logger.setLevel(FinalLogger.levels.get(FinalLogger.log_level))
  return FinalLogger.logger
 
if __name__ == "__main__":
 logger = FinalLogger.getLogger()
 logger.debug("this is a debug msg!")
 logger.info("this is a info msg!")
 logger.warn("this is a warn msg!")
 logger.error("this is a error msg!")
 logger.critical("this is a critical msg!")

当前目录下的 final_logger.log内容如下:

复制代码 代码如下:

[DEBUG][][2012-08-12 18:12:23,029]this is a debug msg!
[INFO][][2012-08-12 18:12:23,029]this is a info msg!
[WARNING][][2012-08-12 18:12:23,029]this is a warn msg!
[ERROR][][2012-08-12 18:12:23,029]this is a error msg!
[CRITICAL][][2012-08-12 18:12:23,029]this is a critical msg!

这个final版本,也是我一直用的,读者朋友也可以再加上其他的一些Handler,比如StreamHandler等等来获取更多的log信息,当然也可以将你的log信息通过配置文件来完成。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles