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

logging

先写一个例子:

功能:把不同的信息放在不同的log文件下:

python 复制代码
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

一种常用的操作

python 复制代码
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 消息。

记录变量数据

python 复制代码
import logging
logging.warning('%s before you %s', 'Look', 'leap!')

更改显示消息的格式

python 复制代码
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()是一样的格式:

python 复制代码
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)¶

实例

python 复制代码
  # 定义文件    (生成一个处理器,和一个格式器)
    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,如果没有的话,就要使用默认的值

相关推荐
余道各努力,千里自同风10 分钟前
CSS实现文本自动平衡text-wrap: balance
前端·css
xiaohanbao0913 分钟前
day29 python深入探索类装饰器
开发语言·python·学习·机器学习·pandas
Yvonne爱编码34 分钟前
CSS- 4.3 绝对定位(position: absolute)&学校官网导航栏实例
前端·css·html·html5·hbuilder
CryptoRzz1 小时前
股票数据源对接技术指南:印度尼西亚、印度、韩国
数据库·python·金融·数据分析·区块链
胖哥真不错1 小时前
Python实现NOA星雀优化算法优化卷积神经网络CNN回归模型项目实战
python·cnn·卷积神经网络·项目实战·cnn回归模型·noa星雀优化算法
繁依Fanyi1 小时前
ImgShrink:摄影暗房里的在线图片压缩工具开发记
开发语言·前端·codebuddy首席试玩官
卓律涤1 小时前
【找工作系列①】【大四毕业】【复习】巩固JavaScript,了解ES6。
开发语言·前端·javascript·笔记·程序人生·职场和发展·es6
love530love2 小时前
【笔记】记一次PyCharm的问题反馈
ide·人工智能·windows·笔记·python·pycharm
梦醒沉醉2 小时前
MCP(一)——QuickStart
python·mcp
照物华2 小时前
httpx[http2] 和 httpx 的核心区别及使用场景如下
python·httpx