logging模块

'''
handler 名称:位置: 作用
StreamHandler: 日志输出到流
FIleHandler: 日志输出到文件
RotatingHandle: 日志回滚方式, 支持日志文件最大数量和日志文件回滚

'''

'''
logger = logging.getLogger('')
logger.setLevel(logging.INFO)
handler = logging.FileHandler('logs.txt')
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s -%(levelname)s -%(lineno)d - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
logger.addHandler(console)
logger.info('test12334444444')
'''


'''
日志回滚
'''
logger = logging.getLogger('')
Rthandler = RotatingFileHandler('demo.txt', maxBytes=10*1024*1024, backupCount=3)
formatter = logging.Formatter('%(asctime)s -%(levelname)s -%(lineno)d - %(message)s')
Rthandler.setFormatter(formatter)
logger.addHandler(Rthandler)
logger.setLevel(logging.DEBUG)
logging.debug('dsfhsdjhfsdjhdsf')


#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Desc 用于记录日志信息
import os
import logging
from logging import handlers
from logging.handlers import TimedRotatingFileHandler
from bmg.conf import project_settings as settings

_format = logging.Formatter("%(asctime)s %(filename)s %(lineno)s %(levelname)s - %(message)s",
"%Y-%m-%d %H:%M:%S")


def get_logger(file_name, formatter=_format):
if not file_name.endswith('.log'):
file_name = file_name + '.log'
path_name = os.path.join(settings.LOG_DIR, file_name)
logger = logging.getLogger(file_name)
if not logger.handlers:
logger.setLevel(logging.DEBUG)
log_file_handler = handlers.RotatingFileHandler(path_name,maxBytes=settings.FILE_MAX_SIZE, backupCount=3)
log_file_handler.setFormatter(formatter)
logger.addHandler(log_file_handler)

stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
return logger
posted @ 2019-06-17 10:10  xiaogao2700c  阅读(119)  评论(0编辑  收藏  举报