一、Logger模块

  • logging.basicConfig函数
 可通过具体参数来更改logging模块默认行为,可用参数有
filename: 用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
filemode: 文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format: 指定handler使用的日志显示格式。
datefmt: 指定日期时间格式。
level: 设置rootlogger的日志级别
stream: 用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET format参数中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(module)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s 用户输出的消

举例:

 import logging
logging.basicConfig(level=logging.DEBUG,
format='[%(name)s]:[%(asctime)s] [%(filename)s|%(funcName)s] [line:%(lineno)d] %(levelname)-8s: %(message)s',
datefmt='%Y-%m-%d %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')
logging.error('error message')
logging.critical('critical message')

结果:

  [root]:[2015-07-03 13:37:40] [test12.py|<module>] [line:13] DEBUG   : This is debug message
[root]:[2015-07-03 13:37:40] [test12.py|<module>] [line:14] INFO : This is info message
[root]:[2015-07-03 13:37:40] [test12.py|<module>] [line:15] WARNING : This is warning message
[root]:[2015-07-03 13:37:40] [test12.py|<module>] [line:16] ERROR : error message
[root]:[2015-07-03 13:37:40] [test12.py|<module>] [line:17] CRITICAL: critical message
 logging分为4个模块: loggers, handlers, filters, and formatters
● loggers: 提供应用程序调用的接口
● handlers: 把日志发送到指定的位置
● filters: 过滤日志信息
● formatters: 格式化输出日志
Logger
Logger.setLevel() 设置日志级别
Logger.addHandler()和Logger.removeHandler() 增加和删除日志处理器
Logger.addFilter()和Logger.removeFilter() 增加和删除过滤器
Logger.debug(), Logger.info(), Logger.warning(), Logger.error(), and Logger.critical() 创建不同的级别的日志
getLogger() 获取日志的根实例
Handler
setLevel() 设置日志级别
setFormatter() 设置输出格式
addFilter() and removeFilter() 增加和删除过滤器
Formatter
默认形式为: %Y-%m-%d %H:%M:%S.
格式为: %()s
  • logging.getLogger函数
 import logging
log = logging.getLogger('yinjia')
logging.basicConfig(level=logging.DEBUG,
format='[%(name)s]:[%(asctime)s] [%(filename)s|%(funcName)s] [line:%(lineno)d] %(levelname)-8s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='myapp.log',
filemode='w') log.debug('This is debug message')
log.info('This is info message')
log.warning('This is warning message')
log.error('error message')
log.critical('critical message')
输出结果:
[yinjia]:[2015-07-03 14:14:07] [test12.py|<module>] [line:12] DEBUG : This is debug message
[yinjia]:[2015-07-03 14:14:07] [test12.py|<module>] [line:13] INFO : This is info message
[yinjia]:[2015-07-03 14:14:07] [test12.py|<module>] [line:14] WARNING : This is warning message
[yinjia]:[2015-07-03 14:14:07] [test12.py|<module>] [line:15] ERROR : error message
[yinjia]:[2015-07-03 14:14:07] [test12.py|<module>] [line:16] CRITICAL: critical message
返回一个logger对象,如果没有指定名字将返回root logger
  • logging.getLogger函数

以ERROR级别记录日志消息,异常跟踪信息将被自动添加到日志消息里。Logger.exception通过用在异常处理块中,例如:

 import logging
log = logging.getLogger('yinjia')
logging.basicConfig(level=logging.DEBUG,
format='[%(name)s]:[%(asctime)s] [%(filename)s|%(funcName)s] [line:%(lineno)d] %(levelname)-8s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='myapp.log',
filemode='w') try:
raise Exception,'This is a exception'
except:
log.exception('This is debug message') #异常信息被自动添加到日志消息中 输出结果:
[yinjia]:[2015-07-03 14:24:43] [test12.py|<module>] [line:15] ERROR : This is debug message
Traceback (most recent call last):
File "D:/PycharmProjects/untitled/test12.py", line 13, in <module>
raise Exception,'This is a exception'
Exception: This is a exception
  • 其它函数
 import logging
log = logging.getLogger('yinjia')
logging.basicConfig(level=logging.DEBUG,
format='[%(name)s]:[%(asctime)s] [%(filename)s|%(funcName)s] [line:%(lineno)d] %(levelname)-8s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='myapp.log',
filemode='w') # 再创建一个handler,用于输出到控制台
console = logging.StreamHandler()
# 定义handler的输出格式formatter
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
# 给logging添加handler
logging.getLogger('').addHandler(console)
logging.info('Jackdaws love my big sphinx of quartz.') log.debug('This is debug message')
log.info('This is info message')
log.warning('This is warning message')
log.error('error message')
log.critical('critical message') 控制台输出结果:
root : INFO Jackdaws love my big sphinx of quartz.
yinjia : INFO This is info message
yinjia : WARNING This is warning message
yinjia : ERROR error message
yinjia : CRITICAL critical message
文件输出结果同上例,只多了一行root用户记录。

另一种方法举例:

 import logging
# 创建一个logger
logger = logging.getLogger('yinjia')
logger.setLevel(logging.DEBUG) format = '[%(name)s]:[%(asctime)s] [%(filename)s|%(funcName)s] [line:%(lineno)d] %(levelname)-8s: %(message)s'
fmt = '[%(asctime)-12s] [%(filename)s][line:%(lineno)d] [%(levelname)8s]: %(message)s' # 创建一个handler,用于输出到控制台
console = logging.StreamHandler() # 创建一个handler,用于写入日志文件
fp = logging.FileHandler('D:\PycharmProjects\untitled\myapp.log') # 定义handler的输出格式formatter
formatter = logging.Formatter(fmt)
fpmatter = logging.Formatter(format)
console.setFormatter(formatter)
fp.setFormatter(fpmatter) # 给logging添加handler
logger.addHandler(console)
logger.addHandler(fp) # 记录日志
logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')
logger.error('error message')
logger.critical('critical message')
以上可以同时输出到控制台和LOG日志文件。
流程:创建logger->创建handler->定义handler输出格式->给logging添加handler->记录日志

、XML模块

  • 生成XML文件

主要方法:

1、生成XML节点(node)

createElement(“node_name”)

2、给节点添加属性值(Attribute)

node.setAttribute(“att_name”,”arr_value”)

3、节点的标签值(data)

createTextNode(“node_value”)

其中第1、3点创建完节点(节点值)之后,还需使用下面的方法添加到指点的节点位置下面:

prev_node.appendChild(cur_node)

这里的prev_node要添加节点的上一层节点,而cur_node即为当前要添加的节点了。

举例如下:

 from xml.dom import minidom
import os
import os.path filename = os.getcwd() + os.path.sep
print filename doc = minidom.Document()
doc.appendChild(doc.createComment("This is a simple xml."))
booklist = doc.createElement("booklist")
doc.appendChild(booklist) def addBook(newbook):
book = doc.createElement("book")
book.setAttribute("id",newbook["id"]) title = doc.createElement("title")
title.appendChild(doc.createTextNode(newbook["title"]))
book.appendChild(title) author = doc.createElement("author")
name = doc.createElement("name")
firstname = doc.createElement("firstname")
firstname.appendChild(doc.createTextNode(newbook["firstname"]))
lastname = doc.createElement("lastname")
lastname.appendChild(doc.createTextNode(newbook["lastname"]))
name.appendChild(firstname)
name.appendChild(lastname)
author.appendChild(name)
book.appendChild(author) pubdate = doc.createElement("pubdate")
pubdate.appendChild(doc.createTextNode(newbook["pubdate"]))
book.appendChild(pubdate) booklist.appendChild(book) addBook({"id":"","title":"An apple","firstname":"Peter","lastname":"Zhang","pubdate":"2012-1-12"})
addBook({"id":"","title":"Love","firstname":"Mike","lastname":"Li","pubdate":"2012-1-10"})
addBook({"id":"","title":"Steve.Jobs","firstname":"Tom","lastname":"Wang","pubdate":"2012-1-19"})
addBook({"id":"","title":"Harry Potter","firstname":"Peter","lastname":"Chen","pubdate":"2012-11-11"}) f = file(filename + "book.xml","w")
doc.writexml(f)
f.close()

运行结果如下:

 生成XML文件如下:
<?xml version="1.0" ?>
<!--This is a simple xml.-->
<booklist>
<book id="">
<title>An apple</title>
<author>
<name>
<firstname>Peter</firstname>
<lastname>Zhang</lastname>
</name>
</author>
<pubdate>2012-1-12</pubdate>
</book> <book id="">
<title>Love</title>
<author>
<name>
<firstname>Mike</firstname>
<lastname>Li</lastname>
</name>
</author>
<pubdate>2012-1-10</pubdate>
</book> <book id="">
<title>Steve.Jobs</title>
<author>
<name>
<firstname>Tom</firstname>
<lastname>Wang</lastname>
</name>
</author>
<pubdate>2012-1-19</pubdate>
</book> <book id="">
<title>Harry Potter</title>
<author>
<name>
<firstname>Peter</firstname>
<lastname>Chen</lastname>
</name>
</author>
<pubdate>2012-11-11</pubdate>
</book>
</booklist>
  • 解析XML文件
  方法:
minidom.parse(filename):加载读取XML文件
doc.documentElement:获取XML文档对象
node.getAttribute(AttributeName):获取XML节点属性值
node.getElementsByTagName(TagName):获取XML节点对象集合
node.childNodes :返回子节点列表。
node.childNodes[index].nodeValue:获取XML节点值
node.firstChild:访问第一个节点,等价于pagexml.childNodes[0]
返回Node节点的xml表示的文本:
doc = minidom.parse(filename)
doc.toxml('UTF-8')
访问元素属性:
Node.attributes["id"]
a.name #就是上面的 "id"
a.value #属性的值

举例一:

XML文件:

  XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<users>1
<user id="">
<username>Admin</username>
<email>admin@live.cn</email>
<age>23</age>
<sex>男</sex>
</user>
<user id="">
<username>Admin2</username>
<email>admin2@live.cn</email>
<age>22</age>
<sex>男</sex>
</user>
<user id="">
<username>Admin3</username>
<email>admin3@live.cn</email>
<age>27</age>
<sex>男</sex>
</user>
<user id="">
<username>Admin4</username>
<email>admin4@live.cn</email>
<age>25</age>
<sex>女</sex>
</user>
<user id="">
<username>Admin5</username>
<email>admin5@live.cn</email>
<age>20</age>
<sex>男</sex>
</user>
<user id="">
<username>Admin6</username>
<email>admin6@live.cn</email>
<age>23</age>
<sex>女</sex>
</user>
</users>

代码如下:

 from  xml.dom import  minidom

 def get_attrvalue(node, attrname):
return node.getAttribute(attrname) if node else '' def get_nodevalue(node, index = 0):
return node.childNodes[index].nodeValue if node else '' def get_xmlnode(node,name):
return node.getElementsByTagName(name) if node else [] def xml_to_string(filename='D:\PycharmProjects\untitled\wxfrom\user.xml'):
doc = minidom.parse(filename)
return doc.toxml('UTF-8') def get_xml_data(filename='user.xml'):
doc = minidom.parse(filename)
root = doc.documentElement user_nodes = get_xmlnode(root,'user')
user_list=[]
for node in user_nodes:
user_id = get_attrvalue(node,'id')
node_name = get_xmlnode(node,'username')
node_email = get_xmlnode(node,'email')
node_age = get_xmlnode(node,'age')
node_sex = get_xmlnode(node,'sex') user_name =get_nodevalue(node_name[0]).encode('utf-8','ignore')
user_email = get_nodevalue(node_email[0]).encode('utf-8','ignore')
user_age = int(get_nodevalue(node_age[0]))
user_sex = get_nodevalue(node_sex[0]).encode('utf-8','ignore')
user = {}
user['id'] , user['username'] , user['email'] , user['age'] , user['sex'] = (
int(user_id), user_name , user_email , user_age , user_sex
)
user_list.append(user)
return user_list def test_xmltostring():
print xml_to_string() def test_laod_xml():
user_list = get_xml_data()
for user in user_list :
#print user['sex']
print '-----------------------------------------------------'
if user:
user_str='编 号:%d\n用户名:%s\n性 别:%s\n年 龄:%s\n邮 箱:%s\n ' % (int(user['id']) , user['username'], user['sex'] , user['age'] , user['email'])
print user_str
print '=====================================================' if __name__ == "__main__":
test_xmltostring() # 打印输出XML文件
test_laod_xml() # 解析读取数据

解析运行结果如下:

 解析输出结果:
-----------------------------------------------------
编 号:1000001
用户名:Admin
性 别:男
年 龄:23
邮 箱:admin@live.cn
=====================================================
-----------------------------------------------------
编 号:1000002
用户名:Admin2
性 别:男
年 龄:22
邮 箱:admin2@live.cn
=====================================================
-----------------------------------------------------
编 号:1000003
用户名:Admin3
性 别:男
年 龄:27
邮 箱:admin3@live.cn
=====================================================
-----------------------------------------------------
编 号:1000004
用户名:Admin4
性 别:女
年 龄:25
邮 箱:admin4@live.cn
=====================================================
-----------------------------------------------------
编 号:1000005
用户名:Admin5
性 别:男
年 龄:20
邮 箱:admin5@live.cn
=====================================================
-----------------------------------------------------
编 号:1000006
用户名:Admin6
性 别:女
年 龄:23
邮 箱:admin6@live.cn
=====================================================

举例二:

XML文件:

  <?xml version="1.0" ?>
<!--This is a simple xml.-->
<booklist>
<book id="">
<title>An apple</title>
<author>
<name>
<firstname>Peter</firstname>
<lastname>Zhang</lastname>
</name>
</author>
<pubdate>2012-1-12</pubdate>
</book> <book id="">
<title>Love</title>
<author>
<name>
<firstname>Mike</firstname>
<lastname>Li</lastname>
</name>
</author>
<pubdate>2012-1-10</pubdate>
</book> <book id="">
<title>Steve.Jobs</title>
<author>
<name>
<firstname>Tom</firstname>
<lastname>Wang</lastname>
</name>
</author>
<pubdate>2012-1-19</pubdate>
</book> <book id="">
<title>Harry Potter</title>
<author>
<name>
<firstname>Peter</firstname>
<lastname>Chen</lastname>
</name>
</author>
<pubdate>2012-11-11</pubdate>
</book>
</booklist>

代码如下:

 from xml.dom import minidom,Node

 class bookscanner:
def __init__(self,doc):
for child in doc.childNodes :
if child.nodeType == Node.ELEMENT_NODE and child.tagName == "book" :
bookid = child.getAttribute("id")
print "*"*20
print "Book id : " , bookid
self.handle_book(child) def handle_book(self,node):
for child in node.childNodes :
if child.nodeType == Node.ELEMENT_NODE :
if child.tagName == "title":
print "Title : " , self.getText(child.firstChild)
if child.tagName == "author":
self.handle_author(child)
if child.tagName == "pubdate":
print "Pubdate : " , self.getText(child.firstChild) def getText(self,node):
if node.nodeType == Node.TEXT_NODE :
return node.nodeValue
else: return "" def handle_author(self,node):
author = node.firstChild
for child in author.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
if child.tagName == "firstname" :
print "Firstname : ", self.getText(child.firstChild)
if child.tagName == "lastname" :
print "Lastname : " , self.getText(child.firstChild) doc = minidom.parse("D:\PycharmProjects\untitled\wxfrom\\book.xml")
for child in doc.childNodes :
if child.nodeType == Node.COMMENT_NODE:
print "Conment : " , child.nodeValue
if child.nodeType == Node.ELEMENT_NODE:
bookscanner(child)

解析运行结果如下:

  Conment :  This is a simple xml.
********************
Book id : 1001
Title : An apple
Pubdate : 2012-1-12
********************
Book id : 1002
Title : Love
Pubdate : 2012-1-10
********************
Book id : 1003
Title : Steve.Jobs
Pubdate : 2012-1-19
********************
Book id : 1004
Title : Harry Potter
Pubdate : 2012-11-11

最新文章

  1. 使用xib需要记得的小问题
  2. LeetCode Palindrome Permutation II
  3. vc6 编译问题
  4. Multi-line NSAttributedString with truncated text
  5. C# Reflection Type/MethodInfo
  6. Laravel环境配置之安装Homestead
  7. IsolatedStorageException for Silverlight Application
  8. C# excel操作
  9. HTTP 错误 405.0 - Method Not Allowed
  10. C#调用存储过程简单完整例子
  11. 【HDU4010】【LCT】Query on The Trees
  12. C#获取窗口,模拟按键操作
  13. Myclipse 安装 Maven遇见的N个异常
  14. UNIX网络编程——使用select函数编写客户端和服务器
  15. MTK刷机快捷键
  16. 【THUSC2017】【LOJ2982】宇宙广播 计算几何 高斯消元
  17. html 水平竖直居中
  18. IOC 和DI(转载)
  19. 20145208 蔡野 《网络对抗》Exp8 Web基础
  20. Javascript(es2016) import和require用法和区别

热门文章

  1. UVA.11384 Help is needed for Dexter (思维题)
  2. warning: React does not recognize the xxx prop on a DOM element
  3. memchr函数
  4. HDU 2655 主席树
  5. [技巧篇]11.JavaScript原生态如何获取浏览器请求地址中的参数
  6. [洛谷P2023] [AHOI2009]维护序列
  7. Value does not fall within the expected range 值不在预期的范围内
  8. Item 8 覆盖equals时请遵守通用约定
  9. Activity与Service的回收
  10. [uva11991]map和vector的入门