Python 学习日知录(二)- 日志

来源:互联网 发布:青山水利软件价格 编辑:程序博客网 时间:2024/06/11 23:55

Python 学习日知录(二)- 日志

一直在用python进行FPGA网络调试,也就是通过udp包读写FPGA的一些内部寄存器和外设什么的。最近想对这个简单脚本进行改造,打造一个更称手的工具。

暂时想法如下:
1. 记录调试过程(logging);
2. 录制脚本,载入运行脚本(保存成json格式);
3. 打开时恢复上一次的运行环境;
4. 命令行就可以了;

python 2.7内置的logging模块,记录调试过程基本够用。这两天就学习了这个模块的基本用法,总结如下:

1. 基本用法

既然是日志,时间戳必不可少。因此直接上带时间戳的代码:

# -*- coding:utf8 -*-import loggingimport logging.handlersdef ini_logging(log_file_name):    '''    初始化logging系统    :param log_file_name: 日志文件    :return:    '''    logger = logging.getLogger()    logger.setLevel(logging.DEBUG)    rh = logging.handlers.TimedRotatingFileHandler(log_file_name, 'D')    fm = logging.Formatter("%(asctime)s  %(levelname)s - %(message)s", "%Y-%m-%d %H:%M:%S")    rh.setFormatter(fm)    logger.addHandler(rh)def write_reg(addr, value):  # 写寄存器    logging.info('write reg %02x : %02x' % (addr, value))def read_reg(addr, len):  # 读寄存器    ret = 128  # 假设的返回值,实际从网络获取    logging.info('read reg %02x : %02x' % (addr, ret))if __name__ == '__main__':    ini_logging('testlog.log')    logging.info('Start')    write_reg(100, 16)    read_reg(100,1)    logging.info('End')

运行该脚本,获得的日志文件如下:

2017-06-20 23:44:33  INFO - Start2017-06-20 23:44:33  INFO - write reg 64 : 102017-06-20 23:44:33  INFO - read reg 64 addr : 802017-06-20 23:44:33  INFO - End

2. 一些有用的东西

2.1 日志等级

日志一共分成5个等级,从低到高分别是:
DEBUG
INFO
WARNING
ERROR
CRITICAL

分别对应五种方法:

    class Logger:        def debug(self, msg, *args, **kwargs): ...        def info(self, msg, *args, **kwargs): ...        def warn(self, msg, *args, **kwargs): ...        def error(self, msg, *args, **kwargs): ...        def critical(self, msg, *args, **kwargs): ...

logger.setLevel(logging.DEBUG)中,可以指定打印的最低级别。

2.2 打印格式

fm = logging.Formatter()中设置。格式如下:

"%(asctime)s  %(levelname)s - %(message)s", "%Y-%m-%d %H:%M:%S"

预定义的内容如下:

name comment %(name)s Name of the logger (logging channel) %(levelno)s Numeric logging level for the message (DEBUG,INFO, WARN, ERROR, CRITICAL) %(levelname)s Text logging level for the message (“DEBUG”, “INFO”,”WARN”, “ERROR”, “CRITICAL”) %(pathname)s Full pathname of the source file where the logging call was issued (if available) %(filename)s Filename portion of pathname %(module)s Module from which logging call was made %(lineno)d Source line number where the logging call was issued (if available) %(created)f Time when the LogRecord was created (time.time() return value) %(asctime)s Textual time when the LogRecord was created %(msecs)d Millisecond portion of the creation time %(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded (typically at application startup time) %(thread)d Thread ID (if available) %(message)s The result of record.getMessage(), computed just as the record is emitted

参考文献:
1. python 日志模块 logging 详解
2. 够用的 Python 写日志的知识——标准日志模块logging简介
3. PEP 282 – A Logging System

原创粉丝点击