python - logging module Basics

Part of the code in this article is based on python changed their official documents accompanying translation howto logging

1.Basic Logging Tutorial

Logging software is running, track events. Software developer to confirm the occurrence of specific events by calling the logging. Developers with a message describing a certain time, specific description can contain variable data (because every time an event occurs, the variables may be different). In addition different degrees of importance in different events, and the importance can be described by the level or severity.

1.1. When to use logging

Logging library provides a set of functions for convenience simply logging, including debug (), info (), warning (), error () and critical (). The following table shows when to use what function logging:

Task you want to perform The best tool for the task
Display a program (or script) using conventional methods at the command line print()
Report the occurrence of a regular event (operation) in the program logging.info() (or logging debug())
A warning for a particular event logging.warning() (or warnings.warn())
Report an error on a specific run-time events raise an exception
Without exception is raised when the report of the error suppression logging.error(),logging.exception(),logging.critical()

logging function is named based on their level, described as follows:

Level When it's used
DEBUG For more information, usually only of interest when diagnosing problems.
INFO Sure everything
WARNING Indicate the occurrence of unexpected things, or indicate there was a problem in the near future (such as "insufficient disk space"). The software is based upon the expected work
ERROR Because of a more serious problem, the software can not perform some functions
CRITICAL Serious error indicating the program itself may not continue to run.

Which, WARNING is the default level, which means that only greater than or equal to the level of events will be tracked.
In addition, the easiest way to trace events are printed to the console, another common method is to write them to a log file.

1.2. A simple example

import logging 
logging.warning('Watch out!')  # will be display on the console
logging.info('I told you so')  # won't be display by default 

1.3. Logging to a file

Another very common scenario is log file in the file, let's take a look. Note that we must re-open a python interpreter, but do not then continue to write the above code.

import logging
import os
# 先删除过去的日志文件,否则会追加在后面
if os.path.isfile('./example.log'):
    print('delete the last example.log')
    os.remove('./example.log')
print('create a new example.log')
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')  # all don't display on the console
logging.info('So should this')
logging.warning('And this, too')   # this is the highest level debug < info < waring < error < critical

This example also shows us how to set the threshold level (threshold), the threshold is set to DEBUG in this example, so that all messages are printed out. In addition you can set this threshold at the command line:
--log=INFO

Writing specific code as follows:

# 学习通过args输入loglevel来进行日志判别。
# assuming loglevel is bound to the string value obtained from the
# command line argument. Convert to upper case to allow the user to
# specify --log=DEBUG or --log=debug
parser = argparse.ArgumentParser(description='logging usage:')
parser.add_argument('-l', '--log', default='WARING', type=str,
                    help='input loglevel')
args = parser.parse_args()
loglevel=args.log
# getattr(obj,param1,param2)  获取obj中param1(可以是方法也可以是属性,其中方法后面+括号即可使用),如果没有就返回param2
numeric_level = getattr(logging,loglevel.upper(),None)  # 将DEBUG这些字符串level转化为数字50level,否则输出None
if not isinstance(numeric_level, int):
    raise ValueError('Invalid log level:%s'%loglevel)
logging.basicConfig(level=numeric_level)

In addition basicConfig function calls should debug (), info () these before. Because he is a simple one-time configuration tool, so only the first call will actually do anything, subsequent calls are no operations.
If you run the script several times, example.log messages are added, if you want to restart every time (as I have written above) can also be done in accordance with the following:

logging.basicConfig(filename='example.log',filemode='w',level=logging.DEBUG) 

1.4. Logging from multiple modules

If your program includes multiple modules, the following example shows you how to organize logging:
In myapp.py file, the code is as follows:

# myapp.py
import logging
import mylib

def main():
    logging.basicConfig(filename='myapp.log',level=logging.DEBUG)
    logging.info('Started!')
    mylib.do_something()
    logging.info('Finished!')

if __name__ == '__main__':
    main()

In mylib.py file (i.e. block B), the following code:

# mylib.py
import logging
def do_something():
    logging.info('Doing something!')

Finally prints in myapp.log in:

INFO:root:Started!
INFO:root:Doing something!
INFO:root:Finished!

Above this simple usage, you can only know the print Doing something, but do not know which model is the INFO print. Behind the Advanced logging tutorial speaks.

1.5. Logging variable data

logging module can print variable, use is str.format ({}. format type) and str.Template (% s% d% f types).

1.6. Changing the format of displayed messages

Logging format on printing, is used to change the keywords in basicConfig format =, the following specific example:

logging.basicConfig(format='%(filename)s,%(levelname)s:%(message)s',level=logging.DEBUG)
logging.debug('this message should appear on the console')
logging.info('So should this!')
logging.warning('And this, too')

Print results are as follows:

howto_logging.py,DEBUG:this message should appear on the console
howto_logging.py,INFO:So should this!
howto_logging.py,WARNING:And this, too

Still other conventional logging format model format as follows:

format format Format Description
%(levelno)s Print log level values
%(levelname)s Print the name of the log level
%(pathname)s Print path to the current execution of the program, in fact, sys.argv [0]
%(filename)s Print this executable name
%(funcName)s The current print log function
%(lineno)d Print Log current line number
%(asctime)s Print log time
%(thread)d Print thread ID
%(threadName)s Print Thread name
%(process)d Printing Process ID
%(message)s Print log information

These are the simple logging foundation tutorial, follow the basic official documents howto logging, plus a little bit of your own code and comments.

The official document: https://docs.python.org/3.5/howto/logging.html

Guess you like

Origin www.cnblogs.com/SsoZhNO-1/p/11910805.html