python 通过logging写入日志到文件和控制台的实例
2018-04-28 10:05
1006 查看
如下所示:
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 通过logging写入日志到文件和控制台
- python 通过logging写入日志到文件和控制台
- python logging模块在多进程多日志文件写入时要注意的问题
- 【Python】同时向控制台和文件输出日志logging
- Python同时向控制台和文件输出日志logging的方法 Python logging模块详解
- Python同时向控制台和文件输出日志logging的方法
- 转【Python】同时向控制台和文件输出日志logging
- Python同时向控制台和文件输出日志logging的方法
- sl4j日志可在本地写入控制台和文件,在服务器不能写入文件
- python logging 模块,logger.debug(),logger.info()等写入文件时的核心源码
- python logging 替代print 输出内容到控制台和重定向到文件
- python 通过 socket 发送文件的实例代码
- Python游戏开发-02-生成日志写入文件
- python logging 实现的进程安全的文件回滚日志类
- C# Python 读取txt中的文件,将16进制的数据按照小端方式排列,处理为有符号的数字,并写入text文件;控制台和界面两种方式
- 关于python logging模块日志记录与oss模块文件上传的问题
- python改变日志(logging)存放位置实例
- Qt4使用qInstallMsgHandler函数往控制台和文件中写入日志
- Python学习--文件和存储器的写入和读出实例
- python 获取指定文件夹下所有文件名称并写入列表的实例