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

相关推荐
985小水博一枚呀14 分钟前
【对于Python爬虫的理解】数据挖掘、信息聚合、价格监控、新闻爬取等,附代码。
爬虫·python·深度学习·数据挖掘
立秋678926 分钟前
Python的defaultdict详解
服务器·windows·python
萧鼎39 分钟前
Python第三方库选择与使用陷阱避免
开发语言·python
安冬的码畜日常41 分钟前
【D3.js in Action 3 精译_029】3.5 给 D3 条形图加注图表标签(上)
开发语言·前端·javascript·信息可视化·数据可视化·d3.js
白拾1 小时前
使用Conda管理python环境的指南
开发语言·python·conda
是刃小木啦~1 小时前
三维模型点云化工具V1.0使用介绍:将三维模型进行点云化生成
python·软件工程·pyqt·工业软件
总裁余(余登武)1 小时前
算法竞赛(Python)-万变中的不变“随机算法”
开发语言·python·算法
小白学习日记1 小时前
【复习】HTML常用标签<table>
前端·html
一个闪现必杀技2 小时前
Python练习2
开发语言·python