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

相关文章

Django获取该数据的上一条和下一条方法

使用Django的ORM操作的时候,想要获取本条,上一条,下一条。 初步的想法是写3个ORM,3个ORM如下: 本条:models.Obj.objects.filter(id=n).fi...

python 实现一次性在文件中写入多行的方法

将要写入的内容 构造 进一个list 中,使用writelines()方法 一次性写入。 file_w.writelines(list) file_w.flush() file.c...

使用python 获取进程pid号的方法

保存为.py文件后 运行脚本在后面添加进程名称即可 比如:python proinfo.py qq 即可获取QQ的进程信息,注意不区分大小写 复制代码 代码如下:#-*- encodin...

python如何从文件读取数据及解析

python如何从文件读取数据及解析

读取整个文件: 首先创建一个文件,例如我创建了一个t x t文件了。 然后我想读取这个文件了,我首先将上面的这个文件保存在我即将要创建的Python的文件目录下, 即读取文件成功。...

python批量处理文件或文件夹

本文实例为大家分享了python批量处理文件或文件夹的具体代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- import os,shutil impor...