Logging模块构成

主要分为四个部分:

  • Loggers:提供应用程序直接使用的接口
  • Handlers:将Loggers产生的日志传到指定位置
  • Filters:对输出日志进行过滤
  • Formatters:控制输出格式
import logging

logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='myapp.log',
filemode='w') logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

myapp.log文件中内容为:

Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

详细参数

logging.basicConfig函数各参数:
filename: 指定日志文件名
filemode: 和file函数意义相同,指定日志文件的打开模式,'w'或'a'
format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:
%(levelno)s: 打印日志级别的数值
%(levelname)s: 打印日志级别名称
%(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
%(filename)s: 打印当前执行程序名
%(funcName)s: 打印日志的当前函数
%(lineno)d: 打印日志的当前行号
%(asctime)s: 打印日志的时间
%(thread)d: 打印线程ID
%(threadName)s: 打印线程名称
%(process)d: 打印进程ID
%(message)s: 打印日志信息
datefmt: 指定时间格式,同time.strftime()
level: 设置日志级别,默认为logging.WARNING
stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略

把日志打印到文件上和屏幕上

import logging
logger = logging.getLogger("simple_example")
logger.setLevel(logging.DEBUG)
# 建立一个filehandler来把日志记录在文件里,级别为debug以上
fh = logging.FileHandler("spam.log")
fh.setLevel(logging.DEBUG)
# 建立一个streamhandler来把日志打在CMD窗口上,级别为error以上
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# 设置日志格式
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
fh.setFormatter(formatter)
#将相应的handler添加在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")

写个类封装一下

    #! /usr/bin/env python
#coding=gbk
import logging,os
class Logger:
def __init__(self, path,clevel = logging.DEBUG,Flevel = logging.DEBUG):
self.logger = logging.getLogger(path)
self.logger.setLevel(logging.DEBUG)
fmt = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
#设置CMD日志
sh = logging.StreamHandler()
sh.setFormatter(fmt)
sh.setLevel(clevel)
#设置文件日志
fh = logging.FileHandler(path)
fh.setFormatter(fmt)
fh.setLevel(Flevel)
self.logger.addHandler(sh)
self.logger.addHandler(fh) def debug(self,message):
self.logger.debug(message) def info(self,message):
self.logger.info(message) def war(self,message):
self.logger.warn(message) def error(self,message):
self.logger.error(message) def cri(self,message):
self.logger.critical(message) if __name__ =='__main__':
logyyx = Logger('yyx.log',logging.ERROR,logging.DEBUG)
logyyx.debug('一个debug信息')
logyyx.info('一个info信息')
logyyx.war('一个warning信息')
logyyx.error('一个error信息')
logyyx.cri('一个致命critical信息')


**实例化**

   logobj = Logger(‘filename',clevel,Flevel)

Python自动化之logging模块的更多相关文章

  1. Python日志输出——logging模块

    Python日志输出——logging模块 标签: loggingpythonimportmodulelog4j 2012-03-06 00:18 31605人阅读 评论(8) 收藏 举报 分类: P ...

  2. Python自建logging模块

    本章将介绍Python内建模块:日志模块,更多内容请从参考:Python学习指南 简单使用 最开始,我们用最短的代码体验一下logging的基本功能. import logging logger = ...

  3. Python实战之logging模块使用详解

    用Python写代码的时候,在想看的地方写个print xx 就能在控制台上显示打印信息,这样子就能知道它是什么了,但是当我需要看大量的地方或者在一个文件中查看的时候,这时候print就不大方便了,所 ...

  4. Python中的logging模块就这么用

    Python中的logging模块就这么用 1.日志日志一共分成5个等级,从低到高分别是:DEBUG INFO WARNING ERROR CRITICALDEBUG:详细的信息,通常只出现在诊断问题 ...

  5. python中日志logging模块的性能及多进程详解

    python中日志logging模块的性能及多进程详解 使用Python来写后台任务时,时常需要使用输出日志来记录程序运行的状态,并在发生错误时将错误的详细信息保存下来,以别调试和分析.Python的 ...

  6. Python自动化之常用模块

    1 time和datetime模块 #_*_coding:utf-8_*_ __author__ = 'Alex Li' import time # print(time.clock()) #返回处理 ...

  7. Python中的logging模块

    http://python.jobbole.com/86887/ 最近修改了项目里的logging相关功能,用到了python标准库里的logging模块,在此做一些记录.主要是从官方文档和stack ...

  8. python日志记录-logging模块

    1.logging模块日志级别 使用logging模块简单示例: >>>import logging >>>logging.debug("this's a ...

  9. Python自学笔记-logging模块详解

    简单将日志打印到屏幕: import logging logging.debug('debug message') logging.info('info message') logging.warni ...

随机推荐

  1. WCF使用net.tcp寄宿到IIS中

    一.IIS部分 1. 安装WAS,如下图所示: 2. 网站net.tcp协议绑定,如下图所示: 3. 网站启用net.tcp,如下图所示: 二.WCF代码部分 1. DesignCaseService ...

  2. 传统javabean与spring中的bean的区别

    javabean已经没人用了 springbean可以说是javabean的发展, 但已经完全不是一回事儿了 用处不同:传统javabean更多地作为值传递参数,而spring中的bean用处几乎无处 ...

  3. ios上-webkit-overflow-scrolling与position的bug

    如上图,.fb-box是一个大div,包含着页面上的所有元素,包括所看到的那个弹窗.dialog-img,并且设置了height:100%;-webkit-overflow-scrolling:tou ...

  4. How to download a CRX file from the Chrome web store

    如何从 谷歌浏览器商店 离线下载 谷歌浏览器扩展 Simply copying the Chrome store extension url to the following website: htt ...

  5. sql 中的注释

    1.单行注释 “-- ”  即:两个中滑线加一个空格 2.多行注释 "/* ... */" 示例: -- 单行注释 /* 多行注释*/ create table test(id i ...

  6. [转载]敏感词过滤,PHP实现的Trie树

    原文地址:http://blog.11034.org/2012-07/trie_in_php.html 项目需求,要做敏感词过滤,对于敏感词本身就是一个CRUD的模块很简单,比较麻烦的就是对各种输入的 ...

  7. linux 局域网探测工具nmap

    NMap,也就是Network Mapper,是Linux下的网络扫描和嗅探工 具包,其基本功能有三个, 一是探测一组主机是否在线: 其次是扫描主机端口,嗅探所提供的网络服务: 还可以推断主机所用的操 ...

  8. C#.net XML的序列化与反序列化

    /// <summary> /// 将一个对象序列化为XML字符串 /// </summary> /// <param name="o">要序列 ...

  9. MySQL: sql_safe_updates

    在my.cnf中设置sql_safe_updates=1 启动mysqld失败. error log报错: 2018-11-20T14:28:14.567022+08:00 0 [ERROR] unk ...

  10. 如何查找论文是否被SCI,EI检索(转)

      转自 http://blog.sina.com.cn/s/blog_564978430100iqpp.html   学术界,尤其是国内学术界,把SCI,EI看得太重,很多大学都要求博士毕业要有SC ...