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设计】。

相关文章

Ubuntu16.04/树莓派Python3+opencv配置教程(分享)

无论是Windows、Linux、还是树莓派 。配置python3的opencv环境都是让人头大的一件事情,尤其是许多人用pip安装以后,发现opencv虽然装上了,但是却装在了系统原生...

Python的Flask框架的简介和安装方法

请在开始使用 Flask 之前阅读本文。也希望本文能够回答关于 Flask 项目的初衷以及目标,以及 flask 适用的场景(情境)等问题。 什么是 “微”? “微” (“Micro”)...

python-opencv在有噪音的情况下提取图像的轮廓实例

python-opencv在有噪音的情况下提取图像的轮廓实例

对于一般的图像提取轮廓,介绍了一个很好的方法,但是对于有噪声的图像,并不能很好地捕获到目标物体。 比如对于我的鼠标,提取的轮廓效果并不好,因为噪声很多: 所以本文增加了去掉噪声的部分。...

Python 按字典dict的键排序,并取出相应的键值放于list中的实例

方法一: def dict_to_numpy_method1(dict): dict_sorted=sorted(dict.iteritems(), key=lambda d:d[...

python3对接mysql数据库实例详解

python3对接mysql数据库实例详解

Python3 MySQL数据库连接,假设MySQL数据库已经安装好了,并创建好了数据库(后面抽点时间将数据库的安装总结下)。  PyMySQL是Python3中用于连接MyS...