logging模块 

很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug、info、warning、error、critical 5个级别,下面我们看一下怎么用。默认情况下日志级别为warning,只有大于warning的日志才会打印。

模块初识:

#logging初识

import logging

logging.warning("user [James] attempted wrong password more than 3 times")
logging.critical("server is down") # WARNING:root:user [James] attempted wrong password more than 3 times
# CRITICAL:root:server is down

上面的代码是最简单的方式,括号里的内容为打印的信息,logging.后的方法为日志的级别,下面看看logging五个级别的详细信息

如果想把日志写到文件里,也很简单:

#日志打印到文件中

import  logging

logging.basicConfig(filename="example.log",level=logging.INFO,
format="%(asctime)s [%(filename)s:%(lineno)d] %(message)s", datefmt="%m/%d/%Y %H:%M:%S [%A]")
# H 24小时格式 I 12小时格式 A 周几完整 a 周几简写 p AM/PM logging.debug("This message should go to the log file")
logging.info("So should this")
logging.warning("And this ,too")

logging.basicConfig里定义了输入文件路径,输入日志信息的级别,输入的格式,格式可自定义;执行完代码后example.log文件会生成信息如下:

10/31/2016 17:16:17 [Monday] So should this
10/31/2016 17:16:17 [Monday] And this ,too

其中下面这句中的level=loggin.INFO意思是,把日志纪录级别设置为INFO,也就是说,只有比日志是INFO或比INFO级别更高的日志才会被纪录到文件里,在这个例子, 第一条日志是不会被纪录的,如果希望纪录debug的日志,那把日志级别改成DEBUG就行了

如果想同时把log打印在屏幕和文件日志里,就需要了解一点复杂的知识了:

The logging library takes a modular approach and offers several categories of components: loggers, handlers, filters, and formatters.

  • Loggers expose the interface that application code directly uses.
  • Handlers send the log records (created by loggers) to the appropriate destination.
  • Filters provide a finer grained facility for determining which log records to output.
  • Formatters specify the layout of log records in the final output.
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#-Author-Lian import logging #创建logger
logger = logging.getLogger("test_log") #创建logger对象 括号内容随便写
logger.setLevel(logging.INFO) #全局日志级别 ch = logging.StreamHandler() #日志打印到屏幕上
ch.setLevel(logging.DEBUG) #指定ch日志打印级别 fh = logging.FileHandler("access.log") #日志存进文件
fh.setLevel(logging.WARNING) #指定fh日志输入级别 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") #定义日志格式,可写多个 #添加日志格式到ch,fh
ch.setFormatter(formatter)
fh.setFormatter(formatter) #添加ch,fh到logger中
logger.addHandler(ch)
logger.addHandler(fh) logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

全局日志级别为整个程序的底线,局部日志级别要想打印则不能比这个级别再低了

屏幕打印信息:

2016-10-31 17:23:42,988 - test_log - INFO - info message
2016-10-31 17:23:42,988 - test_log - WARNING - warn message
2016-10-31 17:23:42,988 - test_log - ERROR - error message
2016-10-31 17:23:42,988 - test_log - CRITICAL - critical message

access.log:

2016-10-31 17:02:06,223 - test_log - WARNING - warn message
2016-10-31 17:02:06,224 - test_log - ERROR - error message
2016-10-31 17:02:06,224 - test_log - CRITICAL - critical message

日志所有的格式:

重要的几个格式:%(lineno)d 输出打印日志代码行 ,%(process)d输出打印日志的进程ID ,%(thread)d输出打印日志的线程ID

日志实例:http://www.cnblogs.com/lianzhilei/p/6513230.html

生产应用(屏幕打印,日志文件写入):

import logging
from logging.handlers import RotatingFileHandler handler = RotatingFileHandler('test.log', maxBytes=20*1024*1024, backupCount=200,encoding='utf-8')
handler.setLevel(logging.INFO)
formatter = logging.Formatter('[%(asctime)s] [%(filename)s:%(lineno)d] %(levelname)s %(message)s')
handler.setFormatter(formatter)
logging.basicConfig(datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG)
logger = logging.getLogger()
logger.addHandler(handler) logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

生产应用(多进程下日志记录)

from cloghandler import ConcurrentRotatingFileHandler

rotateHandler = ConcurrentRotatingFileHandler(logConfig['filePath'], "a", 20 * 1024 * 1024, 200)
rotateHandler.setLevel(logging.INFO)
formatter = logging.Formatter('[%(asctime)s] [process:%(process)s] [%(filename)s:%(lineno)d] %(levelname)s %(message)s')
rotateHandler.setFormatter(formatter)
log = logging.getLogger()
log.addHandler(rotateHandler)
log.setLevel(logging.INFO)

模块安装:

pip install ConcurrentLogHandler

 

import logging

try:
11 +a
except Exception as e:
# logging.error("user [James] attempted wrong password more than 3 times")
logging.error("user [James] attempted wrong password more than 3 times",exc_info=True) # ERROR:root:user [James] attempted wrong password more than 3 times
# Traceback (most recent call last):
# File "Z:/workbanch/move_file.py", line 10, in <module>
# 11 +a
# NameError: name 'a' is not defined

  

Python开发【模块】:logging日志的更多相关文章

  1. python中的logging日志模块

    日志是程序不可或缺的一部分.它可以记录程序的运行情况,帮助我们更便捷地发现问题,而python中的logging日志模块给我们提供了这个机会. logging给我们提供了五种函数用来输出日志:debu ...

  2. Python标准模块--logging

    1 logging模块简介 logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级.日志保存路径.日志文件回滚等:相比print,具备如下优点: 可以通过设置不同 ...

  3. Python标准模块--logging(转载)

    转载地址:http://www.cnblogs.com/zhbzz2007/p/5943685.html#undefined Python标准模块--logging 1 logging模块简介 log ...

  4. Python入门之logging日志模块以及多进程日志

    本篇文章主要对 python logging 的介绍加深理解.更主要是 讨论在多进程环境下如何使用logging 来输出日志, 如何安全地切分日志文件. 1. logging日志模块介绍 python ...

  5. python开发模块基础:异常处理&hashlib&logging&configparser

    一,异常处理 # 异常处理代码 try: f = open('file', 'w') except ValueError: print('请输入一个数字') except Exception as e ...

  6. Python标准模块logging

    http://blog.csdn.net/fxjtoday/article/details/6307285 开发Python, 一直以来都是使用自己编写的logging模块. 比较土...... 今天 ...

  7. python基础语法13 内置模块 subprocess,re模块,logging日志记录模块,防止导入模块时自动执行测试功能,包的理论

    subprocess模块: - 可以通过python代码给操作系统终端发送命令, 并且可以返回结果. sub: 子    process: 进程 import subprocess while Tru ...

  8. python之scrapy模块logging日志

    1.知识点 """ logging : scrapy: settings中设置LOG_LEVEL="WARNING" settings中设置LOG_F ...

  9. Python常用模块--logging

    (转载) 原文:http://www.cnblogs.com/dahu-daqing/p/7040764.html 1 logging模块简介 logging模块是Python内置的标准模块,主要用于 ...

  10. python hashlib模块 logging模块 subprocess模块

    一 hashlib模块 import hashlib md5=hashlib.md5() #可以传参,加盐处理 print(md5) md5.update(b'alex') #update参数必须是b ...

随机推荐

  1. php纯原生实现数组二分法

    代码如下 $arr = [1,3,5,7,9];//$arr = range(1,10000);var_dump(find($arr, 2)); function find(array $arr, $ ...

  2. u3d调用自己的dll

    原文地址:http://blog.sina.com.cn/s/blog_62f7cb730100zhhf.html 首先用vc建立一个dll工程 然后在里面建立一个testunity.h文件.内容如下 ...

  3. Oracle之唯一性约束(UNIQUE Constraint)使用方法具体解释

    Oracle | PL/SQL唯一索引(Unique Constraint)使用方法 1 目标 用演示样例演示怎样创建.删除.禁用和使用唯一性约束. 2 什么是唯一性约束? 唯一性约束指表中一个字段或 ...

  4. js 去掉空格.回车.换行

    Jquery:$("#accuracy").val($("#accuracy").val().replace(/\ +/g,""));//去 ...

  5. mysql的引擎myisam和innodb的区别

    1. MYISAM和INNODB的不同?答:主要有以下几点区别:   a)构造上的区别     MyISAM在磁盘上存储成三个文件,其中.frm文件存储表定义:.MYD (MYData)为数据文件:. ...

  6. JavaScript------自定义string.replaceAll()方法

    代码:: 注意:原始的replace()方法只能替换第一个字符串check String.prototype.replaceAll = function (s1, s2) { return this. ...

  7. Don‘t talk.Just do it.

    对于算法,自己掌握的还是不多.并且我发现对于一个算法的理解非常重要.也许你会发现你貌似会用某总算法但是,他一旦变形,自己就无从下手. 还有就是对于算法.最好每次都自己敲,这样不仅能添加对于算法的熟度. ...

  8. python2.0 s12 day8 _ 堡垒机前戏paramiko模块

    堡垒机前戏 开发堡垒机之前,先来学习Python的paramiko模块,该模块机遇SSH用于连接远程服务器并执行相关操作 paramiko模块是做主机管理的,他模拟了一个ssh. 有两种形式连接形式, ...

  9. mysql触发器的实战经验-不错的文章

    1   引言 Mysql的触发器和存储过程一样,都是嵌入到mysql的一段程序.触发器是mysql5新增的功能,目前线上凤巢系统.北斗系统以及哥伦布系统使用的数据库均是mysql5.0.45版本,很多 ...

  10. react实现的点击拖拽元素效果

    之前用vue做日程管理组件的时候,用到了点击拖拽的效果,即点击元素,鼠标移动到哪里,元素移动到哪里,鼠标松开,拖拽停止,现在在弄react,于是也在想实现这个效果,经过一番折腾,效果出来了,代码如下: ...