python 通过logging写入日志到文件和控制台的实例

yipeiwu_com5年前Python基础

如下所示:

import logging 
 
# 创建一个logger 
logger = logging.getLogger('mylogger') 
logger.setLevel(logging.DEBUG) 
 
# 创建一个handler,用于写入日志文件 
fh = logging.FileHandler('test.log') 
fh.setLevel(logging.DEBUG) 
 
# 再创建一个handler,用于输出到控制台 
ch = logging.StreamHandler() 
ch.setLevel(logging.DEBUG) 
 
# 定义handler的输出格式 
formatter = logging.Formatter('[%(asctime)s][%(thread)d][%(filename)s][line: %(lineno)d][%(levelname)s] ## %(message)s')
fh.setFormatter(formatter) 
ch.setFormatter(formatter) 
 
# 给logger添加handler 
logger.addHandler(fh) 
logger.addHandler(ch) 
 
# 记录一条日志 
logger.info('foorbar') 

关于formatter的配置,采用的是%(<dict key>)s的形式,就是字典的关键字替换。提供的关键字包括:

Format Description
%(name)s Name of the logger (logging channel).
%(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).
%(levelname)s Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').
%(pathname)s Full pathname of the source file where the logging call was issued (if available).
%(filename)s Filename portion of pathname.
%(module)s Module (name portion of filename).
%(funcName)s Name of function containing the logging call.
%(lineno)d Source line number where the logging call was issued (if available).
%(created)f Time when the LogRecord was created (as returned by time.time()).
%(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
%(asctime)s Human-readable time when the LogRecord was created. By default this is of the form “2003-07-08 16:49:45,896” (the numbers after the comma are millisecond portion of the time).
%(msecs)d Millisecond portion of the time when the LogRecord was created.
%(thread)d Thread ID (if available).
%(threadName)s Thread name (if available).
%(process)d Process ID (if available).
%(message)s The logged message, computed as msg % args.

以上这篇python 通过logging写入日志到文件和控制台的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

浅谈Python中的数据类型

数据类型: float — 浮点数可以精确到小数点后面15位 int — 整型可以无限大 bool — 非零为true,零为false list — 列表 Float/Int: 运...

pytorch之添加BN的实现

pytorch之添加BN的实现

pytorch之添加BN层 批标准化 模型训练并不容易,特别是一些非常复杂的模型,并不能非常好的训练得到收敛的结果,所以对数据增加一些预处理,同时使用批标准化能够得到非常好的收敛结果,这...

分析Python的Django框架的运行方式及处理流程

分析Python的Django框架的运行方式及处理流程

之前在网上看过一些介绍Django处理请求的流程和Django源码结构的文章,觉得了解一下这些内容对开发Django项目还是很有帮助的。所以,我按照自己的逻辑总结了一下Django项目的...

Python turtle画图库&&画姓名实例

Python turtle画图库&&画姓名实例

*****看一下我定义的change()和run()函数****** 绘图坐标体系: 作用:设置主窗体的大小和位置 turtle.setup(width, height, sta...

Python实现好友全头像的拼接实例(推荐)

Python实现好友全头像的拼接实例(推荐)

微信好友全头像 话不多说,直接上代码 import itchat import math import PIL.Image as Image import os itchat.a...