python logging模块使用总结
1. 内置 logging模块
日志级别
- CRITICAL 50
 - ERROR 40
 - WARNING 30
 - INFO 20
 - DEBUG 10
 
logging.basicConfig()函数中的具体参数含义
- filename:指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中;
 - filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“w”还可指定为“a”;
 - format:指定handler使用的日志显示格式;
 - datefmt:指定日期时间格式。,格式参考strftime时间格式化(下文)
 - level:设置rootlogger的日志级别
 - stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
 
format参数用到的格式化信息
| 参数 | 描述 | 
|---|---|
| %(name)s | Logger的名字 | 
| %(levelno)s | 数字形式的日志级别 | 
| %(levelname)s | 文本形式的日志级别 | 
| %(pathname)s | 调用日志输出函数的模块的完整路径名,可能没有 | 
| %(filename)s | 调用日志输出函数的模块的文件名 | 
| %(module)s | 调用日志输出函数的模块名 | 
| %(funcName)s | 调用日志输出函数的函数名 | 
| %(lineno)d | 调用日志输出函数的语句所在的代码行 | 
| %(created)f | 当前时间,用UNIX标准的表示时间的浮 点数表示 | 
| %(relativeCreated)d | 输出日志信息时的,自Logger创建以 来的毫秒数 | 
| %(asctime)s | 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 | 
| %(thread)d | 线程ID。可能没有 | 
| %(threadName)s | 线程名。可能没有 | 
| %(process)d | 进程ID。可能没有 | 
| %(message)s | 用户输出的消息 | 
使用logging打印日志到标准输出
import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
使用logging.baseConfig()将日志输出到文件
import os
logging.basicConfig(
	filename=os.path.join(os.getcwd(),'all.log'),
	level=logging.DEBUG,
	format='%(asctime)s  %(filename)s : %(levelname)s  %(message)s',  # 定义输出log的格式
	filemode='a',
	datefmt='%Y-%m-%d %A %H:%M:%S',
)
logging.debug('this is a message')
2. 自定义Logger
设置按照日志文件大小自动分割日志写入文件
import logging
from logging import handlers
class Logger(object):
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'crit': logging.CRITICAL
    }
    def __init__(self, filename, level='info', when='D', backCount=3,
                 fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)  # 设置日志格式
        self.logger.setLevel(self.level_relations.get(level))  # 设置日志级别
        # 向控制台输出日志
        stream_handler = logging.StreamHandler()
        stream_handler.setFormatter(format_str)
        self.logger.addHandler(stream_handler)
        # 日志按文件大小写入文件
        # 1MB = 1024 * 1024 bytes
        # 这里设置文件的大小为500MB
        rotating_file_handler = handlers.RotatingFileHandler(
            filename=filename, mode='a', maxBytes=1024 * 1024 * 500, backupCount=5, encoding='utf-8')
        rotating_file_handler.setFormatter(format_str)
        self.logger.addHandler(rotating_file_handler)
log = Logger('all.log', level='info')
log.logger.info('[测试log] hello, world')
按照间隔日期自动生成日志文件
import logging
from logging import handlers
class Logger(object):
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'crit': logging.CRITICAL
    }
    def __init__(self, filename, level='info', when='D', backCount=3,
                 fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)  # 设置日志格式
        self.logger.setLevel(self.level_relations.get(level))  # 设置日志级别
        # 往文件里写入
        # 指定间隔时间自动生成文件的处理器
        timed_rotating_file_handler = handlers.TimedRotatingFileHandler(
            filename=filename, when=when, backupCount=backCount, encoding='utf-8')
        # 实例化TimedRotatingFileHandler
        # interval是时间间隔,backupCount是备份文件的个数,如果超过这个个数,就会自动删除,when是间隔的时间单位,单位有以下几种:
        # S 秒
        # M 分
        # H 小时、
        # D 天、
        # W 每星期(interval==0时代表星期一)
        # midnight 每天凌晨
        timed_rotating_file_handler.setFormatter(format_str)  # 设置文件里写入的格式
        self.logger.addHandler(timed_rotating_file_handler)
        # 往屏幕上输出
        stream_handler = logging.StreamHandler()
        stream_handler.setFormatter(format_str)
        self.logger.addHandler(stream_handler)
log = Logger('all.log', level='info')
log.logger.info('[测试log] hello, world')
3. logging 模块在Flask中的使用
我在使用Flask的过程中看了很多Flask关于logging的文档,但使用起来不是很顺手,于是自己就根据Flask的官方文档写了如下的log模块,以便集成到Flask中使用。
restful api 项目目录:
.
├── apps_api
│   ├── common
│   ├── models
│   └── resources
├── logs
├── migrations
│   └── versions
├── static
├── templates
├── test
└── utils
└── app.py
└── config.py
└── exts.py
└── log.py
└── manage.py
└── run.py
└── README.md
└── requirements.txt
log.py 文件
# -*- coding: utf-8 -*-
import logging
from flask.logging import default_handler
import os
from logging.handlers import RotatingFileHandler
from logging import StreamHandler
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
LOG_PATH = os.path.join(BASE_DIR, 'logs')
LOG_PATH_ERROR = os.path.join(LOG_PATH, 'error.log')
LOG_PATH_INFO = os.path.join(LOG_PATH, 'info.log')
LOG_PATH_ALL = os.path.join(LOG_PATH, 'all.log')
# 日志文件最大 100MB
LOG_FILE_MAX_BYTES = 100 * 1024 * 1024
# 轮转数量是 10 个
LOG_FILE_BACKUP_COUNT = 10
class Logger(object):
    def init_app(self, app):
				# 移除默认的handler
        app.logger.removeHandler(default_handler)
        formatter = logging.Formatter(
            '%(asctime)s [%(thread)d:%(threadName)s] [%(filename)s:%(module)s:%(funcName)s] '
            '[%(levelname)s]: %(message)s'
        )
        # 将日志输出到文件
        # 1 MB = 1024 * 1024 bytes
        # 此处设置日志文件大小为500MB,超过500MB自动开始写入新的日志文件,历史文件归档
        file_handler = RotatingFileHandler(
            filename=LOG_PATH_ALL,
            mode='a',
            maxBytes=LOG_FILE_MAX_BYTES,
            backupCount=LOG_FILE_BACKUP_COUNT,
            encoding='utf-8'
        )
        file_handler.setFormatter(formatter)
        file_handler.setLevel(logging.INFO)
        stream_handler = StreamHandler()
        stream_handler.setFormatter(formatter)
        stream_handler.setLevel(logging.INFO)
        for logger in (
				# 这里自己还可以添加更多的日志模块,具体请参阅Flask官方文档
                app.logger,
                logging.getLogger('sqlalchemy'),
                logging.getLogger('werkzeug')
        ):
            logger.addHandler(file_handler)
            logger.addHandler(stream_handler)
在exts.py扩展文件中添加log模块
# encoding: utf-8
from log import Logger
logger = Logger()
在app.py 文件中引入logger模块,这个文件是create_app的工厂模块。
# encoding: utf-8
from flask import Flask
from config import CONFIG
from exts import logger
def create_app():
    app = Flask(__name__)
    # 加载配置
    app.config.from_object(CONFIG)
		# 初始化logger
    logger.init_app(app)
    return app
运行run.py
# -*- coding: utf-8 -*-
from app import create_app
app = create_app()
if __name__ == '__main__':
    app.run()
在项目中使用logger模块
from flask import current_app
current_app.logger.info('i am logger info')
current_app.logger.debug('i am logger debug')
$ python run.py
* Serving Flask app "app" (lazy loading)
* Environment: production
	WARNING: This is a development server. Do not use it in a production deployment.
	Use a production WSGI server instead.
* Debug mode: on
2019-07-08 08:15:50,396 [140735687508864:MainThread] [_internal.py:_internal:_log] [INFO]:  * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2019-07-08 08:15:50,397 [140735687508864:MainThread] [_internal.py:_internal:_log] [INFO]:  * Restarting with stat
2019-07-08 08:15:50,748 [140735687508864:MainThread] [_internal.py:_internal:_log] [WARNING]:  * Debugger is active!
2019-07-08 08:15:50,755 [140735687508864:MainThread] [_internal.py:_internal:_log] [INFO]:  * Debugger PIN: 234-828-739
												
											python logging模块使用总结的更多相关文章
- python logging模块可能会令人困惑的地方
		
python logging模块主要是python提供的通用日志系统,使用的方法其实挺简单的,这块就不多介绍.下面主要会讲到在使用python logging模块的时候,涉及到多个python文件的调 ...
 - python logging模块使用
		
近来再弄一个小项目,已经到收尾阶段了.希望加入写log机制来增加程序出错后的判断分析.尝试使用了python logging模块. #-*- coding:utf-8 -*- import loggi ...
 - 读懂掌握 Python logging 模块源码 (附带一些 example)
		
搜了一下自己的 Blog 一直缺乏一篇 Python logging 模块的深度使用的文章.其实这个模块非常常用,也有非常多的滥用.所以看看源码来详细记录一篇属于 logging 模块的文章. 整个 ...
 - (转)python logging模块
		
python logging模块 原文:http://www.cnblogs.com/dahu-daqing/p/7040764.html 1 logging模块简介 logging模块是Python ...
 - Python logging 模块学习
		
logging example Level When it's used Numeric value DEBUG Detailed information, typically of interest ...
 - python logging—模块
		
python logging模块 python logging提供了标准的日志接口,python logging日志分为5个等级: debug(), info(), warning(), error( ...
 - Python logging模块无法正常输出日志
		
废话少说,先上代码 File:logger.conf [formatters] keys=default [formatter_default] format=%(asctime)s - %(name ...
 - 0x03 Python logging模块之Formatter格式
		
目录 logging模块之Formatter格式 Formater对象 日志输出格式化字符串 LogRecoder对象 时间格式化字符串 logging模块之Formatter格式 在记录日志是,日志 ...
 - 0x01 Python logging模块
		
目录 Python logging 模块 前言 logging模块提供的特性 logging模块的设计过程 logger的继承 logger在逻辑上的继承结构 logging.basicConfig( ...
 - Python Logging模块的简单使用
		
前言 日志是非常重要的,最近有接触到这个,所以系统的看一下Python这个模块的用法.本文即为Logging模块的用法简介,主要参考文章为Python官方文档,链接见参考列表. 另外,Python的H ...
 
随机推荐
- 3DMax模型输入到WPF中运行
			
原文:3DMax模型输入到WPF中运行 其实看看笔者文章之前,可以在网上搜索下将3Dmax模型输入到WPF的办法,大部分结果都是这篇文章.这篇文章呢?有点麻烦,就是我们3Dmax模型转换到Blend的 ...
 - Ubuntu下可以直接安装mingw(sudo apt-get install mingw32 mingw32-binutils mingw32-runtime,附例子,简单好用,亲测成功)good
			
Mingw:在Linux系统下编译Windows的程序 Ubuntu下可以直接安装:sudo apt-get install mingw32 mingw32-binutils mingw32-runt ...
 - C++ string的那些坑,C++ string功能补充(类型互转,分割,合并,瘦身) ,c++ string的内存本质(简单明了的一个测试)
			
1. size_type find_first_of( const basic_string &str, size_type index = 0 ); 查找在字符串中第一个与str中的某个字符 ...
 - ASP.NET CORE系列【六】Entity Framework Core 之数据迁移
			
原文:ASP.NET CORE系列[六]Entity Framework Core 之数据迁移 前言 最近打算用.NET Core写一份简单的后台系统,来练练手 然后又用到了Entity Framew ...
 - .Net中使用数据库(sqlite)的大体流程(简单向)
			
说来数据库,各种语言各种数据库在操作上大体无异,基本都是连接数据库.操作数据库.关闭数据库连接的流程,不过Sqlite由于是单文件数据库,相比其他服务器的数据库连接更简单,只需要给定数据库文件的路径即 ...
 - centos 6 yum源记录,离线下载rpm包的办法
			
wget -O /etc/yum.repos.d/CentOS6-Base-163.repo http://mirrors.163.com/.help/CentOS6-Base-163.repo rp ...
 - SQLServer2008-2012开启远程连接的配置方法
			
一.远程连接端口设置(很关键的一步)1.在服务器上打开SQL Server Configuration Manager.选择SQL Server配置管理器->SQL Server 网络配置-&g ...
 - android x86 7.0 32bit调试apk时出现的错误
			
detected problems with app native libraries libavcodec.so:text relocationslibavutil.solibswresample. ...
 - GIS基础软件及操作(九)
			
原文 GIS基础软件及操作(九) 练习九.水文分析 水文分析:根据DEM提取河流网络,计算流水累积量.流向.根据指定的流域面积大小自动划分流域 水文分分析工具 (1)通过Arctoolbox:水文分析 ...
 - Centos重启关机命令
			
Linux centos重启命令: 1.reboot 普通重启 2.shutdown -r now 立刻重启(root用户使用) 3.shutdown -r 10 过10分钟自动重启(root用户 ...