pythonlog文件
A. python logging 源文件在哪
首先,想到的是更改logging.basicConfig(filename=logfilename)参数,来实现变更日志文件名的目的。编写代码如下:
log_fmt = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s'
for i in range(1,4):
filename = str.format('mylog%d.txt' % i)
logging.basicConfig(format=log_fmt, level=logging.DEBUG, filename=filename)
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')12345678
运行结果没有达到预期的效果,只有日志文件mylog1.txt被创建,mylog2.txt和mylog3.txt都未被创建,连续3次的输出的内容都写入mylog1.txt中。说明logging.basicConfig()设置属性具有全局性,第一次设置之后,之后再设置将不再生效。查看官方文档,也确实是如此。
B. python中log文件和txt文件的区别
没区别啊。
log.txt是txt文件。
run.log是log文件。但两个只是后缀格式的不同。都是普通文本文件。没什么特别的。
log是日志的意思
C. Python 将运行结果保存到log文件中遇到的问题
这个简单啊。通过来管道输出到另一源个程序里去,另外一个程序同时打印并输出到out.log
这是我常用的办法。
还有一个笨办法,用自己的myprint代替所有的print语句。这样你可以同时输出到屏幕与文件了。
第三个办法是通过logging。这个模块支持多个listener,可以同时输出到屏幕与文件以及网络。
D. python 使用logging,生成的log文件是什么编码格式脚本的编码格式决定系统的编码格式决定
log的文件当然是byte格式。或者是无格式的。汉字编码取决于你自己设定内的类型。
#coding:utf-8这个东容西,只在python2下有效果。还需要编程器配合。你使用python自带的idle当然是没有问题的。
log中的汉字是一定要编码的。不编码你存贮不了。
编辑器本身的缺省编码格式要与你的源代码编码一致,不然看到的就是乱码。如果是idle,它会根据python脚本自动识别。
不过有些编辑器是有些不智能的。它不能理解python脚本第一行的提示。所以有时候,觉着很别扭自己要手工保持编辑器的编码与源码一致。还需要维护那个coding:utf-8
不过python3已将这一句去掉了。源代码全部要求使用utf-8编码(也许是utf-16),我很少用python3
E. python里的logging怎么写多个文件
an example:
#coding:utf-8
#filename:cfg/logger.yml
version:1
formatters:
simple:
format:'%(asctime)s-%(name)s-%(levelname)s-%(message)s'
consolefmt:
format:'%(name)s-%(levelname)s-%(message)s'
handlers:
console:
class:logging.StreamHandler
formatter:consolefmt
level:WARNING
stream:ext://sys.stdout
ownerloggerfile:
class:logging.handlers.RotatingFileHandler
formatter:simple
level:INFO
filename:log/billingcodeowner.log
maxBytes:1048576
backupCount:3
phnloggerfile:
class:logging.handlers.RotatingFileHandler
formatter:simple
level:INFO
filename:log/phnparser.log
maxBytes:1048576
backupCount:3
loggers:
billingcodeowner:
level:DEBUG
handlers:[ownerloggerfile]
propagate:no
phoneparser:
level:DEBUG
handlers:[console,phnloggerfile]
propagate:no
root:
level:DEBUG
handlers:[console,phnloggerfile]
usage in python application:
importlogging
importlogging.config
importcodecs
importyaml
logging.config.dictConfig(codecs.open("cfg/logger.yml",'r','utf-8').read())
logger=logging.getLogger("billingcodeowner")
F. python的日志,如何做到一天是单独一个日志,并且定期清理
创建以日期为文件的log文件(如:20140911.log),写日志前判断存放日志路径是否存在以当天日期为文件名的文件,如果存在添加日志信息,不存在就创建,在写日志信息。
定期清理亦可以按照此思路来做
G. python中log info 是什么文件
a. 利用sys.stdout将print行导向到你定义的日志文件中,例如:
import sys# make a of original stdout routestdout_backup = sys.stdout# define the log file that receives your log infolog_file = open("message.log", "w")# redirect print output to log filesys.stdout = log_fileprint "Now all print info will be written to message.log"# any command line that you will execute...
log_file.close()# restore the output to initial patternsys.stdout = stdout_backupprint "Now this will be presented on screen"
b. 利用logging模块(规范化日志输出,推荐!!)
由于logging模块的功能比较多,下面就放一些文档里介绍的简单的例子,更详细具体的用法请戳这里
需求
最好的实现方式
故障调查或者状态监测 logging.info()或logging.debug()(后者常用于针对性检测诊断的目的)
特定运行事件发出警告 logging.warning()
报告错误抑制不出发异常(常见于长时间运行的服务器进程的错误处理程序) logging.error(), logging.exception()或者logging.critical()
而以下是根据事件的严重性程度而应采取的logging函数的建议:
程度
使用场景
DEBUG 获得诊断问题是具体的信息
INFO 确认程序是否按正常工作
WARNING 在程序还正常运行时获取发生的意外的信息,这可能会在之后引发异常(例如磁盘空间不足)
ERROR 获取程序某些功能无法正常调用这类严重异常的信息
CRITICAL 获取程序无法继续运行的这类最严重异常信息
默认的等级是WARNING,也就是说logging函数在没有特别配置的前提下只追踪比WARNING程度更严重的异常。
下面就用一些例子来具体说明如何用logging函数记录日志信息:
# this is a simple exampleimport logging# define the log file, file mode and logging levellogging.basicConfig(filename='example.log', filemode="w", level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
查看example.log文件可以看到以下信息:
DEBUG:root:This message should go to the log fileINFO:root:So should thisWARNING:root:And this, too
从多个文件记录日志
# myapp.pyimport loggingimport mylibdef main():
logging.basicConfig(filename='myapp.log', level=logging.INFO)
logging.info('Started')
mylib.do_something()
logging.info('Finished')if __name__ == '__main__':
main()
# mylib.pyimport loggingdef do_something():
logging.info('Doing something')
输出的信息为
INFO:root:StartedINFO:root:Doing somethingINFO:root:Finished
改变默认输出信息的格式
import logging# output format: output time - logging level - log messageslogging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s')
logging.warning('This message will appear in python console.')
在python console中直接打印以下输出:
2016-8-2 2:59:11, 510 - WARNING - This message will appear in python console
logging高级用法
可以通过构建logger或者读取logging config文件对logging函数进行任意配置。
构建logger法
- import logging# create loggerlogger = logging.getLogger('simple_example')
- logger.setLevel(logging.DEBUG)# create console handler and set level to debugch = logging.StreamHandler()
- ch.setLevel(logging.DEBUG)# create formatterformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')# add formatter to chch.setFormatter(formatter)# add ch to loggerlogger.addHandler(ch)# 'application' codelogger.debug('debug message')
- logger.info('info message')
- logger.warn('warn message')
- logger.error('error message')
- logger.critical('critical message')
- $ python simple_logging_mole.py2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message2005-03-19 15:10:26,620 - simple_example - INFO - info message2005-03-19 15:10:26,695 - simple_example - WARNING - warn message2005-03-19 15:10:26,697 - simple_example - ERROR - error message2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
读取配置文件法
- import loggingimport logging.config
- logging.config.fileConfig('logging.conf')# create loggerlogger = logging.getLogger('simpleExample')# 'application' codelogger.debug('debug message')
- logger.info('info message')
- logger.warn('warn message')
- logger.error('error message')
- logger.critical('critical message')
- [loggers]
- keys=root,simpleExample
- [handlers]
- keys=consoleHandler
- [formatters]
- keys=simpleFormatter
- [logger_root]
- level=DEBUG
- handlers=consoleHandler
- [logger_simpleExample]
- level=DEBUG
- handlers=consoleHandler
- qualname=simpleExample
- propagate=0[handler_consoleHandler]class=StreamHandlerlevel=DEBUGformatter=simpleFormatterargs=(sys.stdout,)[formatter_simpleFormatter]format=%(asctime)s - %(name)s - %(levelname)s - %(message)sdatefmt= '%m/%d/%Y %I:%M:%S %p'
- $ python simple_logging_config.py2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message2005-03-19 15:38:55,979 - simpleExample - INFO - info message2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message2005-03-19 15:38:56,055 - simpleExample - ERROR - error message2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
以上程序结果会输出到python console中:
其中logging.conf文件格式为:(其实就是将前一种方法的各项配置参数写到logging.conf文件中)
与前面一样,上述文件输出结果为:
H. 有几千个TXT格式的log文件,怎么用Python批量提取每个log文件固定位置的具体数值,输出到一个TXT文件
1.将这些TXT文件先合并
2.找到这些具体数值的特征
3.用正则表达式过滤提取
这阵子正学习python,不介意可以发给我,练着玩
I. python 读取日志文件
#coding:utf-8
#file: FileSplit.py
import os,os.path,time
def FileSplit(sourceFile, targetFolder):
sFile = open(sourceFile, 'r')
number = 100000 #每个小文件中保存100000条数据
dataLine = sFile.readline()
tempData = [] #缓存列表
fileNum = 1
if not os.path.isdir(targetFolder): #如果目标目录不存在,则创建
os.mkdir(targetFolder)
while dataLine: #有数据
for row in range(number):
tempData.append(dataLine) #将一行数据添加到列表中
dataLine = sFile.readline()
if not dataLine :
break
tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + str(fileNum) + ".txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tempData) #将列表保存到文件中
tFile.close()
tempData = [] #清空缓存列表
print(tFilename + " 创建于: " + str(time.ctime()))
fileNum += 1 #文件编号
sFile.close()
if __name__ == "__main__" :
FileSplit("access.log","access")
#coding:utf-8
#file: Map.py
import os,os.path,re
def Map(sourceFile, targetFolder):
sFile = open(sourceFile, 'r')
dataLine = sFile.readline()
tempData = {} #缓存列表
if not os.path.isdir(targetFolder): #如果目标目录不存在,则创建
os.mkdir(targetFolder)
while dataLine: #有数据
p_re = re.compile(r'(GET|POST)\s(.*?)\sHTTP/1.[01]',re.IGNORECASE) #用正则表达式解析数据
match = p_re.findall(dataLine)
if match:
visitUrl = match[0][1]
if visitUrl in tempData:
tempData[visitUrl] += 1
else:
tempData[visitUrl] = 1
dataLine = sFile.readline() #读入下一行数据
sFile.close()
tList = []
for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):
tList.append(key + " " + str(value) + '\n')
tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + "_map.txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tList) #将列表保存到文件中
tFile.close()
if __name__ == "__main__" :
Map("access\\access.log1.txt","access")
Map("access\\access.log2.txt","access")
Map("access\\access.log3.txt","access")
#coding:utf-8
#file: Rece.py
import os,os.path,re
def Rece(sourceFolder, targetFile):
tempData = {} #缓存列表
p_re = re.compile(r'(.*?)(\d{1,}$)',re.IGNORECASE) #用正则表达式解析数据
for root,dirs,files in os.walk(sourceFolder):
for fil in files:
if fil.endswith('_map.txt'): #是rece文件
sFile = open(os.path.abspath(os.path.join(root,fil)), 'r')
dataLine = sFile.readline()
while dataLine: #有数据
subdata = p_re.findall(dataLine) #用空格分割数据
#print(subdata[0][0]," ",subdata[0][1])
if subdata[0][0] in tempData:
tempData[subdata[0][0]] += int(subdata[0][1])
else:
tempData[subdata[0][0]] = int(subdata[0][1])
dataLine = sFile.readline() #读入下一行数据
sFile.close()
tList = []
for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):
tList.append(key + " " + str(value) + '\n')
tFilename = os.path.join(sourceFolder,targetFile + "_rece.txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tList) #将列表保存到文件中
tFile.close()
if __name__ == "__main__" :
Rece("access","access")