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

相关推荐
我穿棉裤了3 分钟前
使用css 给div添加四角线框
前端·css
Mintopia8 分钟前
🤖 通用人工智能(AGI)离 Web 应用还有多远?
前端·javascript·aigc
TH88869 分钟前
一体化负氧离子监测站:实时、精准监测空气中负氧离子浓度及其他环境参数
python
JianZhen✓27 分钟前
面试题名词解析一
前端
会跑的葫芦怪30 分钟前
Web3开发中的前端、后端与合约:角色定位与协作逻辑
前端·web3·区块链
江城开朗的豌豆32 分钟前
TypeScript泛型:让类型也"通用"的魔法
前端·javascript
苏打水com32 分钟前
0基础学前端:100天拿offer实战课(第3天)—— CSS基础美化:给网页“精装修”的5大核心技巧
人工智能·python·tensorflow
江城开朗的豌豆43 分钟前
TypeScript函数:给JavaScript函数加上"类型安全带"
前端·javascript
凌览44 分钟前
Node.js + Python 爬虫界的黄金搭档
前端·javascript·后端
Java 码农1 小时前
vue 使用vueCli 搭建vue2.x开发环境,并且指定ts 和less
前端·vue.js·less