使用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,如果没有的话,就要使用默认的值

相关推荐
小笔学长2 分钟前
Webpack 入门:打包工具的基本使用
前端·webpack·前端开发·入门教程·前端打包优化
黎明初时3 分钟前
react基础框架搭建4-tailwindcss配置:react+router+redux+axios+Tailwind+webpack
前端·react.js·webpack·前端框架
小沐°4 分钟前
vue3-父子组件通信
前端·javascript·vue.js
铅笔侠_小龙虾5 分钟前
Ubuntu 搭建前端环境&Vue实战
linux·前端·ubuntu·vue
yuhaiqun19897 分钟前
发现前端性能瓶颈的巧妙方法:建立“现象归因→分析定位→优化验证”的闭环思维
前端·经验分享·笔记·python·学习·课程设计·学习方法
Python大数据分析@8 分钟前
使用Dify搭建工作流,实现自动化商品采集分析
运维·python·自动化·网络爬虫
code tsunami8 分钟前
如何将 Helium 与 CapSolver 集成,实现无缝 CAPTCHA 自动化解决
运维·数据库·人工智能·爬虫·python·自动化
玄同76510 分钟前
Python 异常捕获与处理:从基础语法到工程化实践的万字深度指南
开发语言·人工智能·python·自然语言处理·正则表达式·nlp·知识图谱
树叶会结冰16 分钟前
TypeScript---循环:要学会原地踏步,更要学会跳出舒适圈
前端·javascript·typescript
quant_198617 分钟前
BTC 行情预警系统实战教程
开发语言·后端·python·websocket·程序人生·金融