MSIPO技术圈 首页 IT技术 查看内容

使用logging模块来记录日志的方法

2024-03-25

logging

先写一个例子:
功能:把不同的信息放在不同的log文件下:

def write_log(channel_number_log,log_info):
    # 定义文件
    file1 = logging.FileHandler(filename=channel_number_log, mode='a', encoding='utf-8')
    fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s", datefmt='%Y-%m-%d %H:%M:%S')
    file1.setFormatter(fmt)
    #定义日志
    logger1 = logging.Logger(name=channel_number_log, level=logging.INFO)
    logger1.addHandler(file1)
    return logger1.info(log_info)

import logging

一种常用的操作

1.可以创建一个新的日志记录器
logger = getLogger(__name__)
2.基础配置
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
3.开始记录
logger.debug('This message should go to the log file')
logger.info('So should this')
logger.warning('And this, too')
logger.error('And non-ASCII stuff, too, like Øresund and Malmö')

突然使用日志记录会有点懵:
这里说一下关于库的使用感受:
再用库的时候,一定要初步的了解一下库的原理,也就是设计思路。知道思路后才能大致了解下为啥这么用
日志模块采用模块化方法,并提供几类组件:
记录器:记录器暴露了应用程序代码直接使用的接口。(就像是一只记录的笔)

处理器:处理器将日志记录(由记录器创建)发送到适当的目标。
过滤器:过滤器提供了更细粒度的功能,用于确定要输出的日志记录。
格式器:格式器指定最终输出中日志记录的样式。
初始化:
logger = logging.getLogger(name)

记录流程:
需求产生记录—判断level—创建记录----过滤器是否拒绝—(处理器)传递给记录器的处理程序

记录器

记住:永远不要直接实例化记录器
应当通过函数 logging.getLogger(name)
多次使用相同的名字调用 getLogger() 会一直返回相同的 Logger 对象的引用

记录器对象上使用最广泛的方法分为两类:配置和消息发送。
Logger.setLevel() 指定记录器将处理的最低严重性日志消息,其中 debug 是最低内置严重性级别, critical 是最高内置严重性级别。 例如,如果严重性级别为 INFO ,则记录器将仅处理 INFO 、 WARNING 、 ERROR 和 CRITICAL 消息,并将忽略 DEBUG 消息。

记录变量数据

import logging
logging.warning('%s before you %s', 'Look', 'leap!')

更改显示消息的格式

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

在这里插入图片描述
在这里插入图片描述

在消息中显示日期/时间
datefmt和time.strftime()是一样的格式:

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

记录器logging.Logger对象属性和方法:

name
level
parent
propagate
handlers
disabled
setlevel
isEnabledFor
getEffectiveLevel()
getChild(suffix)
getchildren()
debug(msg,*args,**kwargs)
info,warning,error,critical,
log,

class logging.Handler

处理句柄具有以下属性和方法。 请注意 Handler 不可直接实例化;该类是被作为更有用的子类的基类

createLock()¶
acquire()
release()
setlevel()
serFormatter()
addfilte(filter)
removefilter(filter)
filter(record)

格式器对象¶:

class logging.Formatter(fmt=None, datefmt=None, style=‘%’, validate=True, *, defaults=None)¶
format(record
formatTime(record, datefmt=None)
formatException
formatStack(stack_info)
class logging.BufferingFormatter(linefmt=None)

**

过滤器对象¶

**
class logging.Filter(name=‘’)
filter(record)

LogRecord 属性

class logging.LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)
包含与被记录的事件相关的所有信息。

模块级函数

logging.getLogger(name=None)
logging.getLoggerClass()
logging.getLogRecordFactory()¶
logging.debug(msg, *args, **kwargs)
logging.info(msg, *args, **kwargs)
logging.warning(msg, *args, **kwargs)
logging.StreamHandler(stream=None)
logging.FileHandler(filename, mode=‘a’, encoding=None, delay=False, errors=None)
logging.NullHandler
logging.handlers.WatchedFileHandler(filename, mode=‘a’, encoding=None, delay=False, errors=None)¶
logging.handlers.BaseRotatingHandler(filename, mode, encoding=None, delay=False, errors=None)
logging.handlers.SocketHandler(host, port)¶
logging.handlers.DatagramHandler(host, port)¶
返回一个 DatagramHandler 类的新实例,该实例旨在与使用 host 与 port 给定地址的远程主机进行通信。
logging.handlers.SysLogHandler(address=(‘localhost’, SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)¶

实例

  # 定义文件    (生成一个处理器,和一个格式器)
    file1 = logging.FileHandler(filename=channel_number_log, mode='a+', encoding='utf-8')
    fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s", datefmt='%Y-%m-%d %H:%M:%S')
    file1.setFormatter(fmt)
    #定义日志(生成一个记录器,利用生成好的处理器进行生成log)
    logger1 = logging.Logger(name=channel_number_log, level=logging.INFO)
    logger1.addHandler(file1)
    return logger1.info(log_info)

配置日志处理器,
记录器最终按照我们配置好的处理器和fmt来收集相关log,如果没有的话,就要使用默认的值

相关阅读

热门文章

    手机版|MSIPO技术圈 皖ICP备19022944号-2

    Copyright © 2024, msipo.com

    返回顶部