import logging
from logging import handlers
def loger(log_name,lev,log_path,when = "H",backCount=168):
"""
同时输出到控制台和文件,并分包保存,达到一定文件数量自动删除
:param log_name:
:param lev: 日志等级
:param log_path: 日志保存的路径
:param when: 分包标准
:param backCount: 最大文件数量
:return:
"""
level_relations = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL
}
lev = level_relations[lev]
logger = logging.getLogger(log_name)
logger.setLevel(lev)
fh = logging.FileHandler(log_path)
fh = handlers.TimedRotatingFileHandler(filename=log_path, when=when, backupCount=backCount,
encoding='utf-8')
fh.setLevel(lev)
ch = logging.StreamHandler()
ch.setLevel(lev)
formatter = logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)
return logger
if __name__ == '__main__':
log = loger("test","info","E:\\PyCharm\\test.log",when="s")
log.info("1111111")
log.debug("22222")
import logging
from logging import handlers
class Logger(object):
level_relations = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL
}
def __init__(self, filename, level='info', when='H', backCount=100,
fmt='%(created)f,%(asctime)s,%(message)s'):
self.logger = logging.getLogger(filename)
format_str = logging.Formatter(fmt)
self.logger.setLevel(self.level_relations.get(level))
th = handlers.TimedRotatingFileHandler(filename=filename, when=when, backupCount=backCount,
encoding='utf-8')
def namer (filename):
fn = filename.split(".")
f_name = "{}_{}.log".format(fn[0],fn[2])
return f_name
th.setFormatter(format_str)
th.namer = namer
self.logger.addHandler(th)
if __name__ == '__main__':
log = Logger('aaaa', level='info')
log.logger.info('11111')