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 错误和异常代码详解

程序中的错误一般被称为 Bug,无可否认,这几乎总是程序员的错。。。 程序员的一生,始终伴随着一件事 - 调试(错误检测、异常处理)。反反复复,最可怕的是:不仅自己的要改,别人的也要改。...

Python编程pygame模块实现移动的小车示例代码

Python编程pygame模块实现移动的小车示例代码

Pygame是跨平台Python模块,专为电子游戏设计,包含图像、声音。建立在SDL基础上,允许实时电子游戏研发而无需被低级语言(如机器语言和汇编语言)束缚。 最近一个星期学习了一下py...

python3 中文乱码与默认编码格式设定方法

python默认编码格式是utf-8。在python2.7中,可以通过sys.setdefaultencoding('gbk')设定默认编码格式,而在python3.3中sys.setd...

ubuntu 18.04 安装opencv3.4.5的教程(图解)

ubuntu 18.04 安装opencv3.4.5的教程(图解)

【写在前面】 这真的是太那个什么了 不管怎么说 做过的东西做个笔记总是好的 花一点点时间做笔记 不然如果哪一天要重新做了 或者哪一天要汇报工作 都不知道该从哪里入手 又要重新来...

轻量级的Web框架Flask 中模块化应用的实现

Flask是一个轻量级的Web框架。虽然是轻量级的,但是对于组件一个大型的、模块化应用也是能够实现的,“蓝图”就是这样一种实现。对于模块化应用的实现,在Flask 0.2版本中进行了设计...