当前位置:   article > 正文

python 多线程读写文件_python 应用logging多线程写多个log文件

python logging 同时写多个文件

python 使用logging多线程写多个log文件

import threading

import time

import logging

import logging.handlers

LEVELS={'notset':logging.DEBUG,

'debug':logging.DEBUG,

'info':logging.INFO,

'warning':logging.WARNING,

'error':logging.ERROR,

'critical':logging.CRITICAL}

LOG_FILENAME = 'test.log'

LOG_BACKUPCOUNT = 5

LOG_LEVEL = 'notset'

def InitLog(file_name,logger):

LOG_FILENAME = file_name

handler = logging.handlers.RotatingFileHandler(LOG_FILENAME,maxBytes=10*1024*1024,backupCount=LOG_BACKUPCOUNT)

#handler = logging.FileHandler(LOG_FILENAME)

formatter = logging.Formatter("[ %(asctime)s ][ %(levelname)s ] %(message)s\n")

handler.setFormatter(formatter)

#logger = logging.getLogger()

logger.addHandler(handler)

logger.setLevel(LEVELS.get(LOG_LEVEL.lower()))

return logger

class t1(threading.Thread):

def __init__(self,threadName):

threading.Thread.__init__(self,name = threadName)

logger1 = logging.getLogger("thread.a")

self.logger = InitLog("thread1.log",logger1)

def run(self):

global i

self.logger.info("test1")

while True:

print '*************hello t1*****************'

self.logger.info("******hello t1******")

self.logger.debug("t1 debug")

self.logger.warning("t1 warning")

self.logger.error("t1 error")

i += 1

print i

if i> 10:

break

time.sleep(3)

self.logger.info("test1 over")

class t2(threading.Thread):

def __init__(self,threadName):

threading.Thread.__init__(self,name = threadName)

logger2 = logging.getLogger("thread.b")

self.logger = InitLog("thread2.log",logger2)

print "self.logger = %s" %self.logger

None

def run(self):

global i

self.logger.info("test2")

while True:

print 'hello t2'

self.logger.info("hello t2")

self.logger.debug("t2 debug")

self.logger.warning("t2 warning")

self.logger.error("t2 error")

i += 1

print i

if i > 10:

break

time.sleep(5)

self.logger.info("test2.over")

i = 0

p1 = t1('p1')

p1.start()

p2 = t2('p2')

p2.start()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/963135
推荐阅读
相关标签
  

闽ICP备14008679号