当前位置: 首页 > 工具软件 > go-logger > 使用案例 >

PytorchCNN项目搭建1---Logger日志模块

沈英勋
2023-12-01


  • 从今天开始,要进行一个简单的PytorchCNN完整的项目搭建,整体的代码在我的github上面可以查阅

  • 这个项目包括基础了logging、argparse、dataset、model、loss、train & test等函数的编写,尽量把每个函数都进行封装,方便调用,我会一一介绍各个函数

今日先记录一下:


Logging Python日志记录工具

日志是对软件执行时所发生事件的一种追踪方式,软件开发人员对他们的代码添加日志调用,借此来指示某事件的发生。

一个事件通过一些包含变量数据的描述信息来描述(比如:每个事件发生时的数据都是不同的)。开发者还会区分事件的重要性(重要性也被称为 等级严重性

所有的Python模块都可以参与日志输出,

Logging提供了一些便利的函数:debug(), info(), warning(), error(), critical()

想要执行的任务最好的工具
命令行或程序的应用,结果显示在控制台print()
对程序的普通操作发生时提交事件报告logging.info()
提出一个警告信息基于一个特殊的运行时事件warning.warn()或logging.warning()
对一个特殊的运行时事件报告错误引发异常
报告错误而不引发异常(如长时间运行中的服务端进行的错误处理)logging.error(), logging.exception(), logging.critical()

日志功能应以所追踪事件级别或严重性而定,各级别适用性如下(以严重性递增):

级别使用情况
DEBUG细节信息,仅当诊断问题时适用
INFO确认程序按预期运行
WARNING表示有已经或即将发生的意外,程序仍能按照预期进行
ERROR由于严重的问题,程序的某些功能不能正常执行
CRITICAL严重的错误,表明程序已不能继续执行

**注:**默认级别为warning

一个简单的例子

import logging
logging.warning('Watch out!')  # will print a message to the console
logging.info('I told you so')  # will not print anything
WARNING:Watch out!
INFO:I told you so

记录日志到文件

import logging
logging.basicConfig(filename='example.log', level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too') 

DEBUG:This message should go to the log file
INFO:So should this
WARNING:And this, too

更改显示消息的格式

import logging
logging.basicConfig(format='%(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')

DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too

在消息中显示时间

logging.basicConfig(format='%(asctime)s %(message)s')
logging.warning('is when this event was logged')
WARNING:is when this event was logged
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%Y/%m/%d %I:%M:%S %p')
logging.warning('is when this event was logged.')
WARNING:is when this event was logged.

进阶教程

日志库采用模块化方法,并提供几类组件:记录器、处理程序、过滤器和格式化程序。

  • 记录器暴露了应用程序代码直接使用的接口。

  • 处理程序将日志记录(由记录器创建)发送到适当的目标。

  • 过滤器提供了更精细的附加功能,用于确定要输出的日志记录。

  • 格式化程序指定最终输出中日志记录的样式。

配置记录器

我们现在要做的就是生成一个记录器,然后进行相应的配置

  1. 定义记录器logger = logging.getLogger()
  2. 指定记录器将处理的最低严重性日志消息 logger.setLevel() 如果设置为INFO,则记录器仅处理INFO、WARNING、ERROR、CRITICAL消息,而忽略DEBUG消息
  3. 从记录器对象中添加或移除处理程序对象:logger.addHandler() logger.removeHandler()
  4. 添加或移除记录器对象中的过滤器: logger.addFilter() logger.removeFilter()
  5. 配置成功后,使用logger.debug() logger.info() logger.warning(), logger.error(), logger.critical()创建日志记录
  6. getLogger() 返回对具有指定名称的记录器实例的引用,如果没有则返回root
  7. setFormatter(fmt=None, datefmt=None, style=’%’) ,选择一个该处理程序使用的Formatter对象,设置fmt,规定格式

Example

# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
2021-02-03 20:48:13,001 - simple_example - DEBUG - debug message
DEBUG:debug message
2021-02-03 20:48:13,004 - simple_example - INFO - info message
INFO:info message
2021-02-03 20:48:13,006 - simple_example - WARNING - warn message
WARNING:warn message
2021-02-03 20:48:13,007 - simple_example - ERROR - error message
ERROR:error message
2021-02-03 20:48:13,009 - simple_example - CRITICAL - critical message
CRITICAL:critical message

为了之后更好的调用,我们把这个写成一个class类,如下所示:

import logging

class Logger(object):
    level_relations = {
        'debug': logging.DEBUG,
        'info' : logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'critical': logging.CRITICAL
    }

    def __init__(self,filename, level='info',
                 fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s : %(message)s'):
        #create a logger
        self.logger = logging.getLogger()
        self.logger.setLevel(self.level_relations.get(level)) #Logger_level 总开关???
        format_str = logging.Formatter(fmt) #set log format

        # create a handler to input
        ch = logging.StreamHandler()
        ch.setLevel(self.level_relations.get(level))
        ch.setFormatter(format_str)

        #create a handler to filer
        fh = logging.FileHandler(filename=filename, mode='a')
        fh.setLevel(self.level_relations.get(level))
        fh.setFormatter(format_str)

        self.logger.addHandler(ch)
        self.logger.addHandler(fh)

def main():
    logger_file = '../cache/log/example.log'
    log = Logger(logger_file, level='debug')
    log.logger.debug('debug')
    log.logger.info('info')
    log.logger.warning('警告')
    log.logger.error('报错')
    log.logger.critical('严重')
    log.logger.critical('************************************************')

if __name__=='__main__':
    main()
    

参考文献

Python官方中文文档

最后感谢我的师兄,是他手把手教我搭建了整个项目,还有实验室一起学习的小伙伴~ 希望他们万事胜意,鹏程万里!

 类似资料: