python logging文件
程序员文章站
2022-07-15 15:49:07
...
ConcurrentLogHandler 0.9.1
在项目部署的时候,往往代码都打包成pyc格式,无法打断点进行debug,所以log日志就显得非常重要,python自带的log功能是把文件写到一个文件里,然而这样也不利于找到指定位置的断点,最好的处理方式就是基于每个py文件生成指定log
import os
import logging
from cloghandler import ConcurrentRotatingFileHandler
class Log(object):
# config可以试dict形式的配置文件或config文件
config = {xxx}
def __init__(self, name=None, log_level='INFO', logger_path=None):
if logger_path is None:
self.logger_path = config.get('log').get('path')
else:
self.logger_path = logger_path
if name:
self.logger_file = '%s/%s' % (self.logger_path, name)
self.logger = logging.getLogger(name)
self.log_level = log_level
self.handler_log()
def handler_log(self):
self.logger.handlers = []
if not os.path.exists(self.logger_path):
os.system('mkdir -p %s' % self.logger_path)
# 3个参数分别是指定的文件名,a表示追加,1M,最多存在5个文件
rotate_handler = ConcurrentRotatingFileHandler(self.logger_file, "a", 1 * 1024 * 1024, 3)
self.logger.addHandler(rotate_handler)
# 设置格式
if self.log_level == 'DEBUG':
self.logger.setLevel(logging.DEBUG)
log_formatter = '%(threadName)s %(thread)s %(asctime)s.%(msecs)03d %(process)d %(levelname)s %(name)s %(funcName)s %(lineno)d [-] %(message)s'
def get_logger(self):
return self.logger
class UserObj(ORMBaseObject):
"""user object
"""
db_model = User
# 此时name传递的是从根目录的绝对路径的文件名
logger = Log(__name__).get_logger()