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被忽略 logging打印信息函数: logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

Note:

# 一个logger可以不断增加handler,不会覆盖,所以都有效。
# 这样会导致,一行log重复在多个文件打印,甚至如果不小心,在终端也会打印几遍。
# 解决办法:
# 最好在增加handler之前,查看下已有的handler列表 def get_logger(name='', level=logging.DEBUG):
logger = logging.getLogger(name)
logger.setLevel(level)
# console output
if len(logger.handlers) == 0: # 避免重复添加
fmt = '%(asctime)-12s - %(levelname)8s - %(message)s'
datefmt = '%m-%d %H:%M'
fmtt = logging.Formatter(fmt, datefmt)
stdHandler = logging.StreamHandler()
stdHandler.setFormatter(fmtt)
stdHandler.setLevel(logging.DEBUG)
logger.addHandler(stdHandler)
return logger # logger.handlers 就是已添加到该logger上的handler列表, 它是个list所以,可以遍历它,然后判断每个handler的类型。也可以直接以数量判断,因为添加什么,添加顺序,自己写的程序自己知道。

https://docs.python.org/3/howto/logging.html#logging-basic-tutorial

更多更好的例子:

https://docs.python.org/3/howto/logging-cookbook.html#logging-cookbook

import logging

# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename='/temp/myapp.log',
filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
datefmt='%m-%d %H:%M'
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s', datefmt)
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console) # Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.') # Now, define a couple of other loggers which might represent areas in your
# application: logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2') logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')

When you run this, on the console you will see

root        : INFO     Jackdaws love my big sphinx of quartz.
myapp.area1 : INFO How quickly daft jumping zebras vex.
myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
myapp.area2 : ERROR The five boxing wizards jump quickly.

and in the file you will see something like

- : root         INFO     Jackdaws love my big sphinx of quartz.
- : myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
- : myapp.area1 INFO How quickly daft jumping zebras vex.
- : myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
- : myapp.area2 ERROR The five boxing wizards jump quickly.

如果你想在多个python 文件中应用相同的logging 配置, 那么只要在主python程序所在的文件中:

# to set the root logger configuration
logger = logging.getLogger()
# or logger = logging.getLogger('')
logger.setLevel(logging.DEBUG) format = '%(asctime)-12s - %(levelname)8s - %(module)s:%(funcName)s:%(lineno)s - %(message)s'
fmt = '%(asctime)-12s - %(levelname)8s - %(message)s'
formatter = logging.Formatter(format)
fmtt = logging.Formatter(fmt) fh = logging.FileHandler(LOG_FILE)
fh.setFormatter(formatter)
fh.setLevel(logging.DEBUG)
logger.addHandler(fh) stdHandler = logging.StreamHandler()
stdHandler.setFormatter(fmtt)
stdHandler.setLevel(logging.DEBUG)
logger.addHandler(stdHandler)

python logging 学习笔记的更多相关文章

  1. 【原】Learning Spark (Python版) 学习笔记(三)----工作原理、调优与Spark SQL

    周末的任务是更新Learning Spark系列第三篇,以为自己写不完了,但为了改正拖延症,还是得完成给自己定的任务啊 = =.这三章主要讲Spark的运行过程(本地+集群),性能调优以及Spark ...

  2. Python Click 学习笔记(转)

    原文链接:Python Click 学习笔记 Click 是 Flask 的团队 pallets 开发的优秀开源项目,它为命令行工具的开发封装了大量方法,使开发者只需要专注于功能实现.恰好我最近在开发 ...

  3. 0003.5-20180422-自动化第四章-python基础学习笔记--脚本

    0003.5-20180422-自动化第四章-python基础学习笔记--脚本 1-shopping """ v = [ {"name": " ...

  4. Python Flask学习笔记之模板

    Python Flask学习笔记之模板 Jinja2模板引擎 默认情况下,Flask在程序文件夹中的templates子文件夹中寻找模板.Flask提供的render_template函数把Jinja ...

  5. Python Flask学习笔记之Hello World

    Python Flask学习笔记之Hello World 安装virtualenv,配置Flask开发环境 virtualenv 虚拟环境是Python解释器的一个私有副本,在这个环境中可以安装私有包 ...

  6. 获取字段唯一值工具- -ArcPy和Python案例学习笔记

    获取字段唯一值工具- -ArcPy和Python案例学习笔记   目的:获取某一字段的唯一值,可以作为工具使用,也可以作为函数调用 联系方式:谢老师,135-4855-4328,xiexiaokui# ...

  7. Python高级学习笔记

    Python高级学习笔记,此笔记中包含Linux操作系统.Html+CSS+JS.网络协议等. 所有思维导图为本人亲手所画,请勿用于商用. 大哥们,求点赞哦. 第一天笔记:链接 第二天笔记:链接 第三 ...

  8. Python入门学习笔记4:他人的博客及他人的学习思路

    看其他人的学习笔记,可以保证自己不走弯路.并且一举两得,即学知识又学方法! 廖雪峰:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958 ...

  9. Python 基础学习笔记(超详细版)

    1.变量 python中变量很简单,不需要指定数据类型,直接使用等号定义就好.python变量里面存的是内存地址,也就是这个值存在内存里面的哪个地方,如果再把这个变量赋值给另一个变量,新的变量通过之前 ...

随机推荐

  1. uploadify 上传

    本来想做一套上传公用的组建的,里面包含文件转码等功能,看来这些都只能后来一步一步加上了,先写下来... 1,引入脚本等 @{ Layout = null; } <!DOCTYPE html> ...

  2. MvvmLight for Xamarin.Forms

    一.Xamarin.Forms 不使用框架时的绑定 需要注意的是BindingContent,不是DataContent <ContentPage xmlns="http://xama ...

  3. 无法解析的外部符号 _WinMain@16 fatal error LNK1120: 1 个无法解析的外部命令

    一,问题描述MSVCRTD.lib(crtexew.obj) : error LNK2019: 无法解析的外部符号 _WinMain@16,该符号在函数 ___tmainCRTStartup 中被引用 ...

  4. SOLVED: GATT callback fails to register

    I finally figured this problem out. The device I am using is a Samsung Galaxy S4 and the actual prob ...

  5. JPA学习---第一节:JPA详解

    一.详解 JPA JPA(Java Persistence API)是Sun官方提出的Java持久化规范.它为Java开发人员提供了一种对象/关系映射工具来管理Java应用中的关系数据.他的出现主要是 ...

  6. 图片轮播插件-carouFredSel

    carouFredSel图片轮播插件基于Jquery,比较常规的轮播插件,支持滚轮及键盘左右按键,加入其它插件可实现更加复杂的特效. 主页地址:http://caroufredsel.dev7stud ...

  7. FZU 2016 summer train I. Approximating a Constant Range 单调队列

    题目链接: 题目 I. Approximating a Constant Range time limit per test:2 seconds memory limit per test:256 m ...

  8. Codeforces Round #321 (Div. 2) D. Kefa and Dishes 状压dp

    题目链接: 题目 D. Kefa and Dishes time limit per test:2 seconds memory limit per test:256 megabytes 问题描述 W ...

  9. 【POJ】【2151】Check the difficulty of problems

    概率DP kuangbin总结中的第8题 一开始题目看错导致想转移方程想错了……想成f[i][j]表示前 i 个队伍中最多的做出来 j 道题的概率……sigh 看了下题解……其实是对于每个队伍 i 单 ...

  10. 【BZOJ】【1385】【Baltic2000】Division expression

    欧几里得算法 普通的求个gcd即可……思路题 因为要求尽量是整数……所以 $\frac{x_1}{x_2*x_3*x_4*....*x_n}$是最大的结果了,因为$x_2$必须为分母,$x_1$必须为 ...