How to Use the Python script log function, python script log

Source: Internet
Author: User

How to Use the Python script log function, python script log

Assume that you want to develop an automated script tool. The project structure is as follows,CommonThispackageIs the implementation of the framework function,ScriptsThe directory is the test case script we have compiled (ignore other unrelated Directories ).

Our requirements for the log function are as follows:

1. For ease of log viewing, each script corresponds to a log file named after the script.

2. You can set the Log Path and the log size saved by each script. For example, if it is set to 5 MB, the oldest log will be automatically overwritten when it is exceeded.

3. Easy to use Log functions, reducing coupling with framework business functions

  

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

  1. Each script must have one log file.In the Log Module, You need to generate a log file based on the name of the use case script. The key issue here is how to obtain the name Of the use case script in the log module.

Common methods for obtaining file names include:os.getcwd(),sys.argv[0], __file__,Let's take a look at the following functions:

First in a file (assumingtest.py) To write the following code:

  

Then in another file (assumingscript1.py)import testAnd then callfuncMethod:

  

Runscript1.py, The result is:

  

Visible,os.getcwd()The directory for executing the script is obtained, sys.argv[0]Is the absolute path name of the script, __file__Is the absolute path name of the file where the code is executed.

Now we know that we should usesys.argv[0]To obtain the name of the execution script. Because the obtained path is an absolute path, you need to do some processing:sys.argv[0].split('/')[-1].split('.')[0]

  2. Log capacity problemsTo automatically overwrite the oldest log after the capacity is exceeded, useloggingInRotatingFileHandlerYou can set the log file size and the number of backups.

So where are the log paths and capacity configurations? Allow users to directly modifyRotatingFileHandlerThe parameter is obviously not good. It is recommended that you do not modify the framework file. You only need to call the interface to write your own script.

The scheme used here is to write configuration information into a file. XML files are suitable for use as configuration files. You can modify the XML file to set the configuration, and the Log Module reads parameters from the XML file.

To facilitate the placement of XML filesCommonName itconfig.xml, Content:

<? Xml version = "1.0" encoding = "UTF-8"?> <Config> <! -- Log storage path --> <logpath> E: \ PythonLog </logpath> <! -- The size of the log file corresponding to each script, in MB --> <logsize> 8 </logsize> <! -- The number of log files saved by each script --> <lognum> 3 </lognum> </config>

Read XML file content, uselxmlThe library is very simple and the code will be provided later.

  

  3. Easy to use Log FunctionsTo reduce coupling with the framework's business functions, it is best to encapsulate the log function and only provide the log recording interface.

The log interface can meet the preceding requirements in the form of a class method. You only need to call the logging interface through the class, which can be called everywhere for ease of use, and no class instance needs to be defined, it is not coupled with the framework business.

With the above analysis, we can implement the Log Module.

Because the log function is also part of the framework, we also put the Log Module inCommonThispackageInCommonCreatelog.pyFile, the Code is as follows:

# Coding: utf-8from lxml import etreeimport logging. handlersimport loggingimport osimport sys # provides the log function class logger: # Read the configuration data in the XML file first # Because of config. xml is placed in the same directory as the current file. Therefore, you can use _ file _ to obtain the directory of the XML file, then splice it into an absolute path # Here we use the lxml library to parse XML root = etree. parse (OS. path. join (OS. path. dirname (_ file _), 'config. xml ')). getroot () # log file storage path logpath = root. find ('logpath '). text # Read Log File capacity, converted to the byte logsize = 1024*1024 * int (root. find ('logsize '). text) # Number of logs read and saved. lognum = int (root. find ('login '). text) # Log File Name: the absolute logname = OS. path. join (logpath, sys. argv [0]. split ('/') [-1]. split ('. ') [0]) # initialize logger log = logging. getLogger () # log format. You can set fmt = logging as needed. formatter ('[% (asctime) s] [% (filename) s] [line: % (lineno) d] [% (levelname) s] % (message) s ', '% Y-% m-% d % H: % M: % s') # output the log to the file. The obtained log name and size are used here, handle1 = logging. handlers. rotatingFileHandler (logname, maxBytes = logsize, backupCount = lognum) handle1.setFormatter (fmt) # output to the screen at the same time for easy observation handle2 = logging. streamHandler (stream = sys. stdout) handle2.setFormatter (fmt) log. addHandler (handle1) log. addHandler (handle2) # set the basic log. Here, it is set to INFO, indicating that only the INFO level and above will print the log. setLevel (logging. INFO) # log interface. You only need to call the interface here. Here, only logs at INFO, WARNING, and ERROR levels are located, you can define more interfaces @ 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

To test, in the scriptscript1Andscript2Respectively write the following code:

from Common.log import *logger.info('This is info')logger.warning('This is warning')logger.error('This is error')

Run two scripts respectively. The console output is:

  

Generated log files:

  

File Content:

  

Now, you can easily use the logger-type log interface to record logs in other framework files or in user scripts. The above describes how to use the Python script log function. I hope this article will help you learn python.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.