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开发【模块】:paramiko

    一.堡垒机前戏 开发堡垒机之前,先来学习Python的paramiko模块,该模块基于SSH用于连接远程服务器并执行相关操作 模块安装 C:\Program Files\Python 3.5\Scri ...

  2. Python开发【模块】:Celery 分布式异步消息任务队列

    Celery 前言: Celery 是一个 基于python开发的分布式异步消息任务队列,通过它可以轻松的实现任务的异步处理, 如果你的业务场景中需要用到异步任务,就可以考虑使用celery, 举几个 ...

  3. Python开发【模块】:re正则

    re模块 序言: re模块用于对python的正则表达式的操作 '.' 默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行 '^' 匹配字符开头,若指定flags ...

  4. Python开发【模块】:matplotlib 绘制折线图

    matplotlib 1.安装matplotlib ① linux系统安装 # 安装matplotlib模块 $ sudo apt-get install python3-matplotlib # 如 ...

  5. Python开发【模块】:logging日志

    logging模块 很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误.警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式 ...

  6. python标准日志模块logging及日志系统设计

    最近写一个爬虫系统,需要用到python的日志记录模块,于是便学习了一下. python的标准库里的日志系统从Python2.3开始支持.只要import logging这个模块即可使用.如果你想开发 ...

  7. python标准日志模块logging的使用方法

    参考地址 最近写一个爬虫系统,需要用到python的日志记录模块,于是便学习了一下.python的标准库里的日志系统从Python2.3开始支持.只要import logging这个模块即可使用.如果 ...

  8. python标准日志模块logging使用

    python的标准库里的日志系统从Python2.3开始支持.只要import logging这个模块即可使用.如果你想开发一个日志系统, 既要把日志输出到控制台, 还要写入日志文件,只要这样使用: ...

  9. Python开发——8.模块

    一.模块 1.模块 (1)定义:一个.py文件就是一个模块 (2)原因:为了防止程序代码越来越长,对函数进行分组放到不同的文件夹里. (3)优点:提高代码的可维护性:模块编写完毕可以被别人引用,也可以 ...

  10. python的日志模块logging和syslog

    syslog模块是在unix环境下工作的模块,不能用于windows,在windows环境下可以使用logging模块. 一.syslog syslog模块可以用于记录系统运行的信息,这个模块提供的方 ...

随机推荐

  1. 【Xcode 4 无法打开 Xcode 5 DP 打开过的工程文件 解决方法】

    试用Xcode 5 DP打开现有工程文件后再用Xcode4打开后 Xcode 4 会进入崩溃模式折腾了几次发现下面的方法可以让工程文件恢复 如果在Xcode5-DP中打开过xib文件需要在侧栏中修改I ...

  2. NYOJ题目20吝啬的国度

    -----------------------------------------n-1条边的无向连通图是一棵树,又因为树上两点之间的路径是唯一的,所以解是唯一的.(注意并不一定是二叉树,所以最好采用 ...

  3. 拉风的服务器监控工具,随时掌握服务器动态,AgileEAS.NET SOA 平台服务器监控工具集介绍

    一.前言 AgileEAS.NET SOA 中间件平台是一款基于基于敏捷并行开发思想和Microsoft .Net构件(组件)开发技术而构建的一个快速开发应用平台.用于帮助中小型软件企业建立一条适合市 ...

  4. nuget packages batch install

    d:\nuget\nuget.exe install EnterpriseLibrary.Common -NoCache -Verbosity detailed -OutputDirectory D: ...

  5. Vue#表单控件绑定

    使用v-model 在表单控件上实现数据双向绑定. 单选:https://jsfiddle.net/miloer/bs49p0fx/ <input type="checkbox&quo ...

  6. Hibernate的一级缓存

    Hibernate的一级缓存 什么是缓存:缓存将数据库/硬盘上文件中数据,放入到缓存中(就是内存中一块空间).当再次使用的使用,可以直接从内存中获取 缓存的好处:提升程序运行的效率.缓存技术是Hibe ...

  7. java发送GET和post请求

    package com.baqingshe.bjs.util; import java.io.BufferedReader; import java.io.IOException; import ja ...

  8. Sharepoint+Office Infopath+快速搭建问卷调查系统

    项目背景 要开发供公司内部使用的N多个在线调查问卷,要求信息在统一的平台上方便跟踪及管理. 公司内部上了Sharepoint系统及大家习惯了使用infopath及Quick app for share ...

  9. CentOS 6.5 下 CDH 5.2.1 集群安装(一)

    集群节点数量3 个 192.168.1.170 cdh-master 192.168.1.171 cdh-slave-1 192.168.1.171 cdh-slave-2 一.安装CentOS6.5 ...

  10. 解决Win8无法升级.NET Framework 3.5.1 提示错误0x800F0906

    搞了好久,发现了这篇文,很清晰,就引用了过来.http://www.xdowns.com/article/239/Article_3065.html 起因是windows8.1装oracle10g提示 ...