python基础--logging模块
很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug(), info(), warning(), error() and critical() 5个级别,下面我们看一下怎么用。
最简单用法
|
1
2
3
4
5
6
7
8
|
import logginglogging.warning("user [alex] attempted wrong password more than 3 times")logging.critical("server is down")#输出WARNING:root:user [alex] attempted wrong password more than 3 timesCRITICAL:root:server is down |
看一下这几个日志级别分别代表什么意思
| Level | When it’s used |
|---|---|
DEBUG |
Detailed information, typically of interest only when diagnosing problems. |
INFO |
Confirmation that things are working as expected. |
WARNING |
An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. |
ERROR |
Due to a more serious problem, the software has not been able to perform some function. |
CRITICAL |
A serious error, indicating that the program itself may be unable to continue running. |
如果想把日志写到文件里,也很简单
|
1
2
3
4
5
6
|
import logginglogging.basicConfig(filename='example.log',level=logging.INFO)logging.debug('This message should go to the log file')logging.info('So should this')logging.warning('And this, too') |
其中下面这句中的level=loggin.INFO意思是,把日志纪录级别设置为INFO,也就是说,只有比日志是INFO或比INFO级别更高的日志才会被纪录到文件里,在这个例子, 第一条日志是不会被纪录的,如果希望纪录debug的日志,那把日志级别改成DEBUG就行了。
|
1
|
logging.basicConfig(filename='example.log',level=logging.INFO) |
感觉上面的日志格式忘记加上时间啦,日志不知道时间怎么行呢,下面就来加上!
|
1
2
3
4
5
6
|
import logginglogging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')logging.warning('is when this event was logged.')#输出12/12/2010 11:46:36 AM is when this event was logged. |
日志格式
|
%(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 |
用户输出的消息 |
如果想同时把log打印在屏幕和文件日志里,就需要了解一点复杂的知识 了
Python 使用logging模块记录日志涉及四个主要类,使用官方文档中的概括最为合适:
logger提供了应用程序可以直接使用的接口;
handler将(logger创建的)日志记录发送到合适的目的输出;
filter提供了细度设备来决定输出哪条日志记录;
formatter决定日志记录的最终输出格式。
logger
每个程序在输出信息之前都要获得一个Logger。Logger通常对应了程序的模块名,比如聊天工具的图形界面模块可以这样获得它的Logger:
LOG=logging.getLogger(”chat.gui”)
而核心模块可以这样:
LOG=logging.getLogger(”chat.kernel”)
Logger.setLevel(lel):指定最低的日志级别,低于lel的级别将被忽略。debug是最低的内置级别,critical为最高
Logger.addFilter(filt)、Logger.removeFilter(filt):添加或删除指定的filter
Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或删除指定的handler
Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():可以设置的日志级别
handler
handler对象负责发送相关的信息到指定目的地。Python的日志系统有多种Handler可以使用。有些Handler可以把信息输出到控制台,有些Logger可以把信息输出到文件,还有些 Handler可以把信息发送到网络上。如果觉得不够用,还可以编写自己的Handler。可以通过addHandler()方法添加多个多handler
Handler.setLevel(lel):指定被处理的信息级别,低于lel级别的信息将被忽略
Handler.setFormatter():给这个handler选择一个格式
Handler.addFilter(filt)、Handler.removeFilter(filt):新增或删除一个filter对象
每个Logger可以附加多个Handler。接下来我们就来介绍一些常用的Handler:
1) logging.StreamHandler
使用这个Handler可以向类似与sys.stdout或者sys.stderr的任何文件对象(file object)输出信息。它的构造函数是:
StreamHandler([strm])
其中strm参数是一个文件对象。默认是sys.stderr
2) logging.FileHandler
和StreamHandler类似,用于向一个文件输出日志信息。不过FileHandler会帮你打开这个文件。它的构造函数是:
FileHandler(filename[,mode])
filename是文件名,必须指定一个文件名。
mode是文件的打开方式。参见Python内置函数open()的用法。默认是’a',即添加到文件末尾。
3) logging.handlers.RotatingFileHandler
这个Handler类似于上面的FileHandler,但是它可以管理文件大小。当文件达到一定大小之后,它会自动将当前日志文件改名,然后创建 一个新的同名日志文件继续输出。比如日志文件是chat.log。当chat.log达到指定的大小之后,RotatingFileHandler自动把 文件改名为chat.log.1。不过,如果chat.log.1已经存在,会先把chat.log.1重命名为chat.log.2。。。最后重新创建 chat.log,继续输出日志信息。它的构造函数是:
RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
其中filename和mode两个参数和FileHandler一样。
maxBytes用于指定日志文件的最大文件大小。如果maxBytes为0,意味着日志文件可以无限大,这时上面描述的重命名过程就不会发生。
backupCount用于指定保留的备份文件的个数。比如,如果指定为2,当上面描述的重命名过程发生时,原有的chat.log.2并不会被更名,而是被删除。
4) logging.handlers.TimedRotatingFileHandler
这个Handler和RotatingFileHandler类似,不过,它没有通过判断文件大小来决定何时重新创建日志文件,而是间隔一定时间就 自动创建新的日志文件。重命名的过程与RotatingFileHandler类似,不过新的文件不是附加数字,而是当前时间。它的构造函数是:
TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
其中filename参数和backupCount参数和RotatingFileHandler具有相同的意义。
interval是时间间隔。
when参数是一个字符串。表示时间间隔的单位,不区分大小写。它有以下取值:
S 秒
M 分
H 小时
D 天
W 每星期(interval==0时代表星期一)
midnight 每天凌晨
import logging logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG) fh = logging.FileHandler('monitor.log')
fh.setLevel(logging.INFO) ch = logging.StreamHandler()
ch.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter) logger.addHandler(fh)
logger.addHandler(ch)
文件自动截断例子 复制代码
import logging from logging import handlers logger = logging.getLogger(__name__) log_file = "timelog.log"
#fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=3)
fh = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3) formatter = logging.Formatter('%(asctime)s %(module)s:%(lineno)d %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) logger.warning("test1")
logger.warning("test12")
logger.warning("test13")
logger.warning("test14")
# -*- coding:utf-8 -*-
__author__ = 'shisanjun' import logging
import sys,os from atm.conf import settings def logger(log_type): log_file="%s" %os.path.join(settings.BASE_DIR,"log",settings.LOG_FILE[log_type]) log_level=settings.LOG_LEVEL logger_var=logging.getLogger(log_type)
logger_var.setLevel(log_level) ch=logging.StreamHandler()
ch.setLevel(log_level) fh=logging.FileHandler(log_file,encoding="utf-8")
fh.setLevel(log_level) #fomatter=logging.Formatter('%(asctime)s %(name)s %(levelname)s - %(message)s')
fomatter=logging.Formatter('%(asctime)s %(levelname)s - %(message)s')
ch.setFormatter(fomatter)
fh.setFormatter(fomatter)
#判断是否有haddler设备已存在,存在就直接反回。如果没有这一步打印日志多份,有多少个hadder就打印几个
if logging._handlers>=1:
return logger_var logger_var.addHandler(ch)
logger_var.addHandler(fh) return logger_var
python基础--logging模块的更多相关文章
- 周末班:Python基础之模块
什么是模块 什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类别: 1 使用python编写 ...
- Python的logging模块详解
Python的logging模块详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.日志级别 日志级别指的是产生的日志的事件的严重程度. 设置一个级别后,严重程度 ...
- python基础——第三方模块
python基础——第三方模块 在Python中,安装第三方模块,是通过包管理工具pip完成的. 如果你正在使用Mac或Linux,安装pip本身这个步骤就可以跳过了. 如果你正在使用Window ...
- python基础——使用模块
python基础——使用模块 Python本身就内置了很多非常有用的模块,只要安装完毕,这些模块就可以立刻使用. 我们以内建的sys模块为例,编写一个hello的模块: #!/usr/bin/env ...
- Python之logging模块
一.引言 之前在写一些小程序的时候想把日志内容打到文件中,所以就自己写了一个logger.py的程序,如下: #!/usr/bin/python # -*- coding=utf-8 -*- impo ...
- python的logging模块
python提供了一个日志处理的模块,那就是logging 导入logging模块使用以下命令: import logging logging模块的用法: 1.简单的将日志打印到屏幕上 import ...
- python的logging模块之读取yaml配置文件。
python的logging模块是用来记录应用程序的日志的.关于logging模块的介绍,我这里不赘述,请参见其他资料.这里主要讲讲如何来读取yaml配置文件进行定制化的日志输出. python要读取 ...
- python中logging模块的用法
很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误.警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,loggin ...
- 二十五. Python基础(25)--模块和包
二十五. Python基础(25)--模块和包 ● 知识框架 ● 模块的属性__name__ # my_module.py def fun1(): print("Hello& ...
随机推荐
- kindeditor<=4.1.5上传漏洞复现
0x00 漏洞描述 漏洞存在于kindeditor编辑器里,你能上传.txt和.html文件,支持php/asp/jsp/asp.net,漏洞存在于小于等于kindeditor4.1.5编辑器中 这里 ...
- Linux及安全实践四——ELF文件格式分析
Linux及安全实践四——ELF文件格式分析 一.ELF文件格式概述 1. ELF:是一种对象文件的格式,用于定义不同类型的对象文件中都放了什么东西.以及都以什么样的格式去放这些东西. 二.分析一个E ...
- 使用JS在textarea在光标处插入内容
// 在光标处插入字符串 // myField 文本框对象 // myValue 要插入的值 function insertAtCursor(myField, myValue) { //IE supp ...
- mysql 5.7 json 字段类型查找、修改
修改 json 里的数组字段 mysql> set @json = '{"test": [{"name": "laravel"}, { ...
- mac 必备工具
iTerm 可以在一个窗口中垂直.水平分割窗口,而不用切换来切换去 一些基本功能如下: 1.分窗口操作:shift+command+d(横向)command+d(竖向) 2.查找和粘贴:command ...
- 题解【CF103D Time to Raid Cowavans】
Description 给一个序列 \(a\) ,\(m\) 次询问,每次询问给出 \(t, k\) .求 \(a_t + a_{t+k}+a_{t+2k}+\cdots+a_{t+pk}\) 其中 ...
- Head内常用标签
一.标签分类 1.1 自闭和标签 自闭和标签只有开头没有结尾,自动闭合: <meta> 标签 <link> 标签 1.2主动闭合标签 有开头也有结尾,是主动闭合的,称为主动闭合 ...
- IDEA Mybatis plugin插件破解
破解文件: 链接:https://pan.baidu.com/s/1J7asfLc5I0RBcoYX3_yNvQ 提取码:kjxv 使用方法: C:\Users\{你的用户名}\.IntelliJId ...
- gitlab的备份与恢复与迁移
一.gitlab的备份1.1 创建备份目录,并授权 1 2 3 4 [root@linux-node1 ~]# mkdir /data/backups/gitlab -p [root@linux-no ...
- 通过xshell/securecrt连接linux上传/下载文件
通过ssh等客户端连接远程linux总会有上传下载的需求,这里分别用Ubuntu和centos展示安装lrzsz软件的命令,使用命令是一致的,这里简单写 1.安装: centos:(注:参数-y中的意 ...