python3 logging 日志记录
# main#coding=utf-8
import logging
from time import sleep
import time
from subprocess import Popen
from threading import Thread
from parseXml import parsexml
from log import log
def command(args, **kwargs):
# 子节点
ch = logging.getLogger('dxdiag.start')
try:
# print('\nargs:{}\
# \nkwargs: {}'.format(args, kwargs))
pro = Popen(args, **kwargs)
except Exception as err:
print('\nargs:{}\
\nkwargs: {}\
\nerror:{}'.format(args, kwargs, err))
ch.exception('启动失败')
return False
else:
return pro
def dxdiag():
# resultFileName
global name
dxdiag = [r'C:\Windows\SysWOW64\dxdiag.exe',
'/dontskip', '/whql:off', '/64bit', '/x', name+'.xml']
d = command(dxdiag)
ch = logging.getLogger('dxdiag')
ch.info('Dxdiag 正在读取系统配置, 请稍候。。。 ')
while True:
d.poll()
if not d.returncode is None: break
sleep(0.25)
if __name__ == '__main__':
# 设置日志父节点, 文件名
logger = log('dxdiag', 'didxag.log')
name = 'config'
a = Thread(target=dxdiag, daemon=True)
a.start()
a.join()
xml = parsexml(name+'.xml')
xml.getData()
xml.saveText(name+'.txt', 'w')
日志配置模块
# coding=utf-8
import logging
# 默认生成的root logger的level是logging.WARNING,低于该级别的就不输出
# 级别排序:CRITICAL > ERROR > WARNING > INFO > DEBUG
class log(object):
def __init__(self, name, file):
self.name = name
self.file = file
self.logger = logging.getLogger(self.name)
self.logger.setLevel(logging.INFO)
# 控制台输出
self.controlHandler = logging.StreamHandler()
self.controlHandler.setLevel(logging.INFO)
self.controlHandler.setFormatter(logging.Formatter(
'%(levelname)s: %(message)s'))
# 文件
self.logHandler = logging.FileHandler(self.file, 'w')
self.logHandler.setLevel(logging.DEBUG)
self.logHandler.setFormatter(logging.Formatter(
'%(asctime)s %(filename)s %(name)s %(levelname)s: %(message)s'))
# 处理器
self.logger.addHandler(self.logHandler)
self.logger.addHandler(self.controlHandler)
解析xml
# coding=utf-8
import logging
import xml.etree.ElementTree as ET
from prettytable import PrettyTable
class parsexml(object):
def __init__(self, xmlName):
try:
self.log = logging.getLogger('dxdiag.parsexml')
self.xmlName = xmlName
self._root = ET.parse(self.xmlName).getroot()
self.sheetList = []
self.sheettitle = []
except Exception as err:
self.log.exception(f'打开文件失败{self.xmlName}')
@staticmethod
def _table(elementTree):
# xml 元素
tb = PrettyTable()
tb.field_names = ["Name", "Data"]
tb.align["Name"] = 'l'
data = [ for each in elementTree]
for row in data:
tb.add_row(row)
return tb
def saveText(self, fileName, mode):
self.log.info(f'正在保存数据 {self.xmlName}')
count = 0
total = len(self.sheetList)
with open(fileName, mode) as fp:
for sheet, title in zip(self.sheetList, self.sheettitle):
# 增加标题
fp.write(sheet.get_string(title=title))
count += 1
# 在最后一个表格之前增加换行符
if count < total: fp.write('\n')
def getData(self):
self.log.info(f'正在解析数据 {self.xmlName}')
si = self._root.find('SystemInformation')
self.sheetList.append(self._table(si))
self.sheettitle.append('SystemInformation')
display = self._root.find('DisplayDevices')
display = display.find('DisplayDevice')
self.sheetList.append(self._table(display[:12]))
self.sheettitle.append('DisplayDevices')
disk = self._root.find('LogicalDisks')
disk = disk.findall('LogicalDisk')
for each in disk:
self.sheetList.append(self._table(each))
self.sheettitle.append('LogicalDisks')
for i in self.sheetList:
print(i)
if __name__ == '__main__':
xml = parsexml('config.xml')
xml.getData()
xml.saveText('config.txt','w') 赞 hrp 发表于 2020-12-11 11:54
赞
{:10_250:}
页:
[1]