Home Backend Development Python Tutorial Using Python script logging functionality

Using Python script logging functionality

Feb 25, 2017 pm 01:20 PM

Suppose you want to develop an automated script tool. The project structure is as follows. CommonThis package is the implementation of the framework function. The Scripts directory is the test case we wrote. Scripts (please ignore other irrelevant directories).

Our requirements for the log function are as follows:

1 In order to facilitate log viewing, each script corresponds to a log file, and the log file is named after the name of the script

  2 The log path and the log capacity saved by each script can be set. For example, if it is set to 5MB, the oldest log will be automatically overwritten after exceeding it

  3 The log function should be easy to use and reduce the coupling with the framework business functions

 Using Python script logging functionality

Now let’s analyze the above requirements one by one.

 1 To implement a log file for each script, you need to generate a log file according to the name of the use case script in the log module. The key issue here is How to get the name of the use case script in the logging module.

Commonly used methods to obtain file names are: os.getcwd(), sys.argv[0], __file__, Let’s take a look at the various functions:

First write the following code in a file (assumed to be test.py):

 Using Python script logging functionality

Then in another file (assumed to be import test in script1.py), and then call the func method:

 Using Python script logging functionality

 Runscript1.py, the result is:

 Using Python script logging functionality

It can be seen that os.getcwd() obtains the directory where the script is executed, sys.argv[0] is the absolute path name of the executed script, __file__ is the absolute path name of the file where the executed code is located.

Now it is clear, we should use sys.argv[0] to get the name of the execution script. Since the absolute path is obtained, some processing needs to be done: sys .argv[0].split('/')[-1].split('.')[0]

 2 Log capacity issue, to automatically overwrite the oldest log after exceeding the capacity, use the RotatingFileHandler class in logging. You can set the size of the log file and the number of backups.

So where are the log path and capacity configuration? It is obviously not good to let users directly modify the parameters of RotatingFileHandler. It is best not to let users modify the framework file. Users only need to call the interface and write their own scripts.

The solution adopted here is to write the configuration information into a file. The XML file is more suitable as a configuration file. The user formulates the configuration by modifying the XML file, and the log module reads parameters from the XML file.

For convenience, put the XML file under Common and name it config.xml. The content is:

<?xml version="1.0" encoding="utf-8"?>

<config>
  <!-- 日志保存路径 -->
  <logpath>E:\PythonLog</logpath>

  <!-- 每个脚本对应的日志文件大小,单位MB -->
  <logsize>8</logsize>

  <!-- 每个脚本保存的日志文件个数 -->
  <lognum>3</lognum>
</config>
Copy after login

Reading the contents of XML files is very simple using the lxml library. The code will be given later.

 

 3 The log function should be easy to use and reduce the coupling with the business functions of the framework. It is best to encapsulate the log function and only provide Just use the logging interface.

The log interface can meet the above requirements in the form of a class method. Users only need to call the logging interface through the class, which can be called anywhere. It is easy to use, and there is no need to define a class instance, and there is no coupling with the framework business.​​

With the above analysis, let’s implement the log module.

Since the logging function is also part of the foundation of the framework, we also put the log module in the Commonpackage and create a new# under Common ##log.py file, the code is as follows:

# coding: utf-8

from lxml import etree
import logging.handlers
import logging
import os
import sys

# 提供日志功能
class logger:
  # 先读取XML文件中的配置数据
  # 由于config.xml放置在与当前文件相同的目录下,因此通过 __file__ 来获取XML文件的目录,然后再拼接成绝对路径
  # 这里利用了lxml库来解析XML
  root = etree.parse(os.path.join(os.path.dirname(__file__), &#39;config.xml&#39;)).getroot()
  # 读取日志文件保存路径
  logpath = root.find(&#39;logpath&#39;).text
  # 读取日志文件容量,转换为字节
  logsize = 1024*1024*int(root.find(&#39;logsize&#39;).text)
  # 读取日志文件保存个数
  lognum = int(root.find(&#39;lognum&#39;).text)

  # 日志文件名:由用例脚本的名称,结合日志保存路径,得到日志文件的绝对路径
  logname = os.path.join(logpath, sys.argv[0].split(&#39;/&#39;)[-1].split(&#39;.&#39;)[0])

  # 初始化logger
  log = logging.getLogger()
  # 日志格式,可以根据需要设置
  fmt = logging.Formatter(&#39;[%(asctime)s][%(filename)s][line:%(lineno)d][%(levelname)s] %(message)s&#39;, &#39;%Y-%m-%d %H:%M:%S&#39;)

  # 日志输出到文件,这里用到了上面获取的日志名称,大小,保存个数
  handle1 = logging.handlers.RotatingFileHandler(logname, maxBytes=logsize, backupCount=lognum)
  handle1.setFormatter(fmt)
  # 同时输出到屏幕,便于实施观察
  handle2 = logging.StreamHandler(stream=sys.stdout)
  handle2.setFormatter(fmt)
  log.addHandler(handle1)
  log.addHandler(handle2)

  # 设置日志基本,这里设置为INFO,表示只有INFO级别及以上的会打印
  log.setLevel(logging.INFO)

  # 日志接口,用户只需调用这里的接口即可,这里只定位了INFO, WARNING, ERROR三个级别的日志,可根据需要定义更多接口
  @classmethod
  def info(cls, msg):
    cls.log.info(msg)
    return

  @classmethod
  def warning(cls, msg):
    cls.log.warning(msg)
    return

  @classmethod
  def error(cls, msg):
    cls.log.error(msg)
    return
Copy after login

Let’s test it, in the scripts

script1 and script2 Write the following codes in :

from Common.log import *

logger.info(&#39;This is info&#39;)
logger.warning(&#39;This is warning&#39;)
logger.error(&#39;This is error&#39;)
Copy after login

Run the two scripts respectively, and the console output is:

 Using Python script logging functionality

 Log file generated:

 Using Python script logging functionality

 File content:

  Using Python script logging functionality

For more articles related to using the Python script log function, please pay attention to the PHP Chinese website!

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Learning Python: Is 2 Hours of Daily Study Sufficient? Learning Python: Is 2 Hours of Daily Study Sufficient? Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Which is part of the Python standard library: lists or arrays? Which is part of the Python standard library: lists or arrays? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python for Web Development: Key Applications Python for Web Development: Key Applications Apr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

See all articles