日志不管对于开发或者运维都是一项非常重要的东西,它可以用来排错,解决故障,统计分析等。本文介绍python中的日志库的用法。日志库:import logging要用日志需要先定义以下东西:1.获取日志名,比如logging.getLogger(__name__)2.定义Handler,比如logging.FileHandler("/var/log/messages")3.设置级别,比如fh.setLevel(logging.DEBUG)4.定义格式,比如formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")5.打印日志,比如LOG.error("python logging test!!")下面给出一段脚本用来输出日志到/var/log/messages和终端。import loggingLOG = logging.getLogger(__name__)formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")fh = logging.FileHandler("/var/log/messages")fh.setLevel(logging.DEBUG)fh.setFormatter(formatter)LOG.addHandler(fh)ch = logging.StreamHandler()ch.setLevel(logging.ERROR)ch.setFormatter(formatter)LOG.addHandler(ch)LOG.error("python logging test!!")
运行下,你会发现/var/log/messages和屏幕上都会有类似“2015-06-28 07:41:41,527 - test - ERROR - python logging test!!”。这是日志的最基本用法,以后会介绍更加复杂点的用法。下面关于Python的文章您也可能喜欢,不妨看看:Python:在指定目录下查找满足条件的文件 http://www.linuxidc.com/Linux/2015-08/121283.htmPython2.7.7源码分析 http://www.linuxidc.com/Linux/2015-08/121168.htm无需操作系统直接运行 Python 代码 http://www.linuxidc.com/Linux/2015-05/117357.htmCentOS上源码安装Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htmPython脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htmPython 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htmPython 的详细介绍:请点这里
Python 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-09/122954.htm