Home >Backend Development >Python Tutorial >Introduction to python packages and logging
Python package and logging log
1. Package
Package: A package with an __init__.py file in a folder is used to manage multiple modules.
The structure of the package is as follows:
bake ├── __init__.py ├── api ├── __init__.py ├── policy.py └── versions.py ├── cmd ├── __init__.py └── manage.py └── db ├── __init__.py └── models.py
Create a test.py at the same level as bake Import policy.py:
import bake.api.policy bake.api.policy.get() #导入的名字太长了,可以起别名 import bake.api.policy as p p.get() #from 导入在__init__.py修改 from . import policy #我们需要在policy文件中向sys.path添加了当前的路径 import os import sys sys.path.insert(os.path.dirname(__file__)) #print(__file__)查看一下 #使用__all__,在__init__.py中 __all__ = ["policy"] #或 from . import policy
Summary:
import package.package.package
from package.package.package import module
Path:
Absolute: import from the outer layer
Relative: import from the current (.) or from the parent (..)
When using relative paths, they must be at the end of the package Outer layer and same level
from package import *
Need to do the operation in __init__.py
python2: The import folder (without __init__.py) will report an error
python3: The import folder (without __init__.py) will not report an error
Related recommendations: "Python Video Tutorial"
二, logging module
The logging module is used to record various statuses of the software, transaction records, error records, login records...
1. Functional simple configuration:
import logging logging.debug('debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message')
By default, python's logging module prints logs to the standard output, and only displays logs greater than or equal to WARNING level, which proves that the default level is WARNING
Log level: CRITICAL > ERROR > WARNING > INFO > DEBUG
2. Flexible configuration of log level, log mode, input location (low configuration version)
Only Write logs and cannot output to the public screen
import logging logging.basicConfig(level = logging.DEBUG, format = '%(astime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s', datefmt = '%Y-%m-%d %H:%M:%S', filename = 'test.log', filemode = 'a') dic = {"key":123} logging.debug(dic) num = 100 logging.info(f"用户余额:{num - 50}") try: num = int(input("请输入数字:")) except Exception as e: logging.warning("e") logging.error('error message') logging.critical('critical message')
The default behavior of the logging module can be changed through specific parameters in the basicConfig() function. The available parameters are:
filename: Use Creates a FiledHandler for the specified file name so that the log will be stored in the specified file.
filemode: File opening mode, this parameter is used when filename is specified. The default value is "a" and can also be specified as "w".
format: Specify the log display format used by the handler.
datefmt: Specify date and time format.
level: Set the logging level
stream: Create a StreamHandler with the specified stream. You can specify the output to
sys.stderr, sys.stdout or file (f=open(‘test.log’,’w’)), the default is sys.stderr. If both filename and stream parameters are listed, the stream parameter will be ignored.
Format strings that may be used in the format parameter:
%(name)s Logger’s name
%(levelno)s numeric form The log level of
%(levelname)s The log level in text form
%(pathname)s The full pathname of the module that calls the log output function, may not have
% (filename)s The file name of the module that calls the log output function
%(module)s The module name that calls the log output function
%(funcName)s The function name that calls the log output function
%(lineno)d The line of code where the statement that calls the log output function is located
%(created)f The current time, expressed as a UNIX standard floating point number representing time
%(relativeCreated)d The number of milliseconds since the Logger was created when outputting log information.
%(asctime)s The current time in the form of a string. The default format is "2003-07-08 16:49:45,896". What follows the comma is the thread ID in milliseconds
%(thread)d. There may be no
%(threadName)s thread names. There may be no
%(process)d process ID. There may not be messages output by
%(message)s users
3.logger object configuration (medium version)
import logging logger = logging.getLogger() # 创建一个logger fh = logging.FileHandler('test.log',mode="a",encoding='utf-8') # 文件 ch = logging.StreamHandler() # 屏幕 formatter = logging.Formatter('%(asctime)s - %(name)s - %(filename)s - [line:%(lineno)d] - %(levelname)s - %(message)s') # 将屏幕和文件都是用以上格式 logger.setLevel(logging.DEBUG) # 设置记录级别 fh.setFormatter(formatter) # 使用自定义的格式化内容 ch.setFormatter(formatter) logger.addHandler(fh) #logger对象可以添加多个fh和ch对象 logger.addHandler(ch) logger.debug('logger debug message') logger.info('logger info message') logger.warning('logger warning message') logger.error('logger error message') logger.critical('logger critical message')
The above is the detailed content of Introduction to python packages and logging. For more information, please follow other related articles on the PHP Chinese website!