时间:2021-05-22
如下所示:
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写入日志到文件和控制台的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例讲述了Python同时向控制台和文件输出日志logging的方法。分享给大家供大家参考。具体如下:python提供了非常方便的日志模块,可实现同时向控制
python作为一门非常容易上手的脚本语言,日志输出更是简单,logging模块,简单的设置配置和属性,就能实现到控制台输出日志,在basicConfig()设
本文实例讲述了python日志logging模块使用方法。分享给大家供大家参考,具体如下:一、从一个使用场景开始开发一个日志系统,既要把日志输出到控制台,还要写
本文实例讲述了C#控制台进行文件读写的方法。分享给大家供大家参考。具体如下:C#控制台进行文件写入:usingSystem;usingSystem.IO;cla
Console.Write表示向控制台直接写入字符串,不进行换行,可继续接着前面的字符写入。Console.WriteLine表示向控制台写入字符串后换行。Co