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感知机实现代码

python感知机实现代码

本文实例为大家分享了python感知机实现的具体代码,供大家参考,具体内容如下 一、实现例子 李航《统计学方法》p29 例2.1 正例:x1=(3,3), x2=(4,3), 负例:x3...

Python复制文件操作实例详解

本文实例讲述了Python复制文件操作用法。分享给大家供大家参考,具体如下: 这里用python实现了一个小型的自动发版本的工具。这个“自动发版本”有点虚, 只是简单地把debug 目录...

python 批量添加的button 使用同一点击事件的方法

python 批量添加的button 使用同一点击事件根据传递的参数进行区分。 def clear_text(): print '我只是个清空而已' def clear_tex...

Python函数基础实例详解【函数嵌套,命名空间,函数对象,闭包函数等】

本文实例讲述了Python函数基础用法。分享给大家供大家参考,具体如下: 一、什么是命名关键字参数? 格式: 在*后面参数都是命名关键字参数。 特点: 1、约束函数的调用者必须按照Kye...

python list语法学习(带例子)

创建:list = [5,7,9]取值和改值:list[1] = list[1] * 5列表尾插入:list.append(4)去掉第0个值并返回第0个值的数值:list.pop(0)去...