py learning packages and logs

The first chapter bag

__Init__.py file contains folders as long as the package is a

Recall that before we did not learn a whole module when the function is written to a file in order to fully reuse will be a feature we use the module, but the module will be more and more slowly. We want to improve the structural program maintainability, on the use of the package will be unified management module

Package can manage multiple modules, which we want to use the bag how to do it?

Use import and from xx import xx

Two methods

2. Absolute path to import

from bake.api  import www   #推荐使用
www.fun()

3. introducing relative path

from  .. api.www import fun #zbb中

fun() #必须在最外层的同级进行导入
#执行
from bake.api.zbb  import fun

The second chapter logging module

Functional simple configuration (most spam)

import logging  
logging.debug('调试')  
logging.info('信息')  
logging.warning('警告')  
logging.error('错误')  
logging.critical('危险')

Python logging module logs the default print to standard output, and only shows a greater than or equal WARNING level logging, logging level indicating that the default to WARNING

(Log level grade CRITICAL> ERROR> WARNING> INFO> DEBUG),

The default log format for the log level: Logger Name: User output messages.

Flexible configuration log level, the log format, output location: (garbage)

import logging  
logging.basicConfig(level=logging.DEBUG,  
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',  
                    datefmt='%a, %d %b %Y %H:%M:%S',  
                    filename='/tmp/test.log',  
                    filemode='w')  

basicConfig () function can be changed by the logging module specific parameters default behavior parameters are available:

  • filename: Creating FiledHandler, such logs are stored in the specified file with the specified file name.
  • filemode: File Open, this parameter is specified in the filename, the default value "a" may also be designated as "w".
  • format: log handler specified display format.
  • datefmt: specify the date and time format.
  • Set logging levels: level
  • stream: Creating StreamHandler with the specified stream. You can specify output to
  • sys.stderr, sys.stdout or file (f = open ( 'test.log', 'w')), default sys.stderr. If both lists the filename and stream two parameters, the stream parameter is ignored.

the format parameter string format may be used :

  • % (Name) s Logger name
  • % (Levelno) s log level digital form
  • % (Levelname) s log level text form
  • % (Pathname) s call to the full path name of the log output function module may not
  • % (Filename) s call log output function module filename
  • % (Module) s call log output function module name
  • Function names% (funcName) s call log output function
  • OK code statements% (lineno) d log output function call where
  • % (Created) f the current time, represented by a standard floating point representation UNIX Time
  • Since the number of milliseconds Logger created when the d output log information% (relativeCreated)
  • % (Asctime) of the current time string s. The default format is "2003-07-0816: 49: 45,896." Milliseconds after the comma
  • % (Thread) d thread ID. Maybe not
  • % (ThreadName) s thread name. Maybe not
  • % (Process) d process ID. Maybe not
  • Message% (message) s user output

logger object configuration (Standard Edition)

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')
import logging

dic = {"key":123}
logging.debug(dic)

num = 100
logging.info(f"用户当前余额:{num - 50}")

try:
    num = int(input("请输入数字:"))
except Exception as e:
    logging.warning("int将字符串转换报错了")
print("12334")

logging.error('我是错误')
logging.critical('我是危险')

Ultimate (regressed)


import os
import logging.config
# 定义三种日志输出格式 开始

standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                  '[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字

simple_format = '在 %(asctime)s %(message)s'

id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'


# log文件的全路径
logfile_path = 'all2.log'

# log配置字典
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
    },
    'filters': {},
    'handlers': {
        #打印到终端的日志
        'stream': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'simple'
        },
        #打印到文件的日志,收集info及以上的日志
        'file': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'formatter': 'standard',
            'filename': None,  # 日志文件
            'maxBytes': 1024*1024*1024,  # 日志大小 5M
            'backupCount': 5,
            'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
        },
    },
    'loggers': {
        #logging.getLogger(__name__)拿到的logger配置
        '': {
            'handlers': ['stream', 'file'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'level': 'DEBUG',
            'propagate': True,  # 向上(更高level的logger)传递
        },
    },
}


def get_logger():
    path = r'F:\s24\day21\liye.log'
    LOGGING_DIC['handlers']['file']['filename'] = path
    logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置
    logger = logging.getLogger(__name__)  # 生成一个log实例
    return logger



def save():
    logger = get_logger()
    logger.info(f'{} 存入300元')  # 记录该文件的运行状态

save()

Guess you like

Origin www.cnblogs.com/zdqc/p/11290500.html