xml地图|网站地图|网站标签 [设为首页] [加入收藏]

皇家娱乐棋牌python实现扫描日志关键字的示例,

来源:http://www.ccidsi.com 作者:最新解决方案 人气:198 发布时间:2019-06-12
摘要:正如所示: 大家在压力测试进程会征集到大多log,怎么着飞快从中找到有用新闻呢?让python脚本帮大家做那部分职业吗! 1. 异常: import logging # 创建一个logger logger = logging.getLogger('my

正如所示:

大家在压力测试进程会征集到大多log,怎么着飞快从中找到有用新闻呢?让python脚本帮大家做那部分职业吗!

1. 异常:

import logging 

# 创建一个logger 
logger = logging.getLogger('mylogger') 
logger.setLevel(logging.DEBUG) 

# 创建一个handler,用于写入日志文件 
fh = logging.FileHandler('test.log') 
fh.setLevel(logging.DEBUG) 

# 再创建一个handler,用于输出到控制台 
ch = logging.StreamHandler() 
ch.setLevel(logging.DEBUG) 

# 定义handler的输出格式 
formatter = logging.Formatter('[%(asctime)s][%(thread)d][%(filename)s][line: %(lineno)d][%(levelname)s] ## %(message)s')
fh.setFormatter(formatter) 
ch.setFormatter(formatter) 

# 给logger添加handler 
logger.addHandler(fh) 
logger.addHandler(ch) 

# 记录一条日志 
logger.info('foorbar') 

废话不说,上代码

一.壹 抛出至极

利用raise关键字抛出11分

raise Exception('This is a exception')

至于formatter的布置,接纳的是%(<dict key>)s的情势,便是字典的严重性字替换。提供的重中之重字回顾:

环境:win10 python2.7.14

一.二 捕获极度

try: 
    return 42 / divideBy 
except ZeroDivisionError: 
    print('Error: Invalid argument.')

try: 
    return 42 / divideBy 
except ZeroDivisionError as e: # 将异常赋值给变量e
    print('Error: '  str(e))
Format Description
%(name)s Name of the logger (logging channel).
%(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).
%(levelname)s Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').
%(pathname)s Full pathname of the source file where the logging call was issued (if available).
%(filename)s Filename portion of pathname.
%(module)s Module (name portion of filename).
%(funcName)s Name of function containing the logging call.
%(lineno)d Source line number where the logging call was issued (if available).
%(created)f Time when the LogRecord was created (as returned by time.time()).
%(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
%(asctime)s Human-readable time when the LogRecord was created. By default this is of the form “2003-07-08 16:49:45,896” (the numbers after the comma are millisecond portion of the time).
%(msecs)d Millisecond portion of the time when the LogRecord was created.
%(thread)d Thread ID (if available).
%(threadName)s Thread name (if available).
%(process)d Process ID (if available).
%(message)s The logged message, computed as msg % args.
#-*- encoding: utf-8 -*-
#author : beihuijie
#version 1.1
import re
import sys
import os
import countTime
def getParameters():
 '''
 get parameters from console command
 '''
 with open(sys.argv[1], "r") as fread:
 lines = fread.readlines()
 keywords=[]
 for line in lines:
  temp = line.split(', ')
  keywords.append(temp)
 for i in range(0, (len(keywords[0]) - 1)):
  print ' Keyword = %s' % keywords[0][i]
 return keywords[0]
def isFileExists(strfile):
 '''
 check the file whether exists
 '''
 return os.path.isfile(strfile)
def Search(keyword, filename):
 '''
 search the keyword in a assign file
 '''
 if(isFileExists(filename) == False):
 print 'Input filepath is wrong,please check again!'
 sys.exit()
 linenum = 1
 findtime = 0
 with open(filename, 'r') as fread:
 lines = fread.readlines()
 for line in lines:
  rs = re.findall(keyword, line, re.IGNORECASE)
  if rs:
  #output linenum of keyword place 
  sys.stdout.write('line:%d '%linenum)
  lsstr = line.split(keyword)
  strlength = len(lsstr)
  findtime = findtime   1
  #print strlength
  for i in range(strlength):
   if(i < (strlength - 1)):
   sys.stdout.write(lsstr[i].strip())
   sys.stdout.write(keyword)
   else:
   sys.stdout.write(lsstr[i].strip()   'n')
  linenum = linenum   1
 print ' ---------------------------------------------------------------------------- '
 print (' Search result: find keyword: %s %d times'%(keyword, findtime))
 print ' ---------------------------------------------------------------------------- '
def executeSearch():
 '''
 this is a execute search method
 '''
 ls = getParameters()
 start = countTime.getTime()
 parameter_number = len(ls)
 print 'Filename = %s ' % ls[parameter_number - 1]
 print '--------------------start search-------------------------'
 if(parameter_number >= 2):
 for i in range(parameter_number - 1):
  Search(ls[i], ls[parameter_number - 1])
 else:
 print 'There is a parameter error occured in executeSearch()!'
 end = countTime.getTime()
 print ' ---------------------------------------------------------------------------- '
 print ' Total cost time: %s'%countTime.formatTime(end - start)
 print ' ============================================================================ '

if __name__=='__main__':
 executeSearch()

2. 断言

assert [条件p], [p不成立时输出的字符串]

禁用断言
python xx.py -O

上述那篇python 通过logging写入日志到文件和调整台的实例正是小编分享给我们的全体内容了,希望能给我们3个参照,也盼望我们多多支持脚本之家。

countTime.py

3. Log(logging模块)

本文由68399皇家赌场发布于最新解决方案,转载请注明出处:皇家娱乐棋牌python实现扫描日志关键字的示例,

关键词: 68399皇家赌场 Python学习笔记

最火资讯