python3 log工具 logutil.py
# -*- coding: utf-8 -*-
import os,sys,traceback
import logging
from logging.handlers import RotatingFileHandler
import getpass
def singleton(cls):
instances = {}
def get_instance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return get_instance()
@singleton
class GConfig:
def __init__(self):
self.logger_filename = "server.log"
self.logger_lv = "INFO"
@singleton
class Logger(object):
def __init__(self):
log_path = os.path.join(os.path.expanduser("."), "logs")
Log_filename = os.path.join(log_path, GConfig.logger_filename)
self.loggername = getpass.getuser()
self.logr = logging.getLogger()
if GConfig.logger_lv.upper().strip() == 'DEBUG':
self.logr.setLevel(logging.DEBUG)
elif GConfig.logger_lv.upper().strip() == 'WARNING':
self.logr.setLevel(logging.WARNING)
elif GConfig.logger_lv.upper().strip() == 'ERROR':
self.logr.setLevel(logging.ERROR)
elif GConfig.logger_lv.upper().strip() == 'CRITICAL':
self.logr.setLevel(logging.CRITICAL)
else:
self.logr.setLevel(logging.INFO)
# self.logr.setLevel(logging.WARNING)
handler = None
if not os.path.isdir(log_path):
try:
os.mkdir(log_path) # create dir if it doesn't exist
except:
raise IOError("Couldn't create \"" + log_path + "\" folder. Check" \
" permissions")
try:
handler = logging.FileHandler(Log_filename, "a")
# create RotatingFileHandler,最多备份1个日志文件,每个日志文件最大20M
handler = RotatingFileHandler(Log_filename, maxBytes = 20*1024*1024,backupCount = 5)
formatter = logging.Formatter("%(asctime)s %(name)s - %(filename)s[line:%(lineno)d] - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
except:
raise IOError("Couldn't create/open file \"" + Log_filename + "\". Check permissions.")
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
if handler:
self.logr.addHandler(handler)
self.logr.addHandler(ch)
if __name__ =="__main__":
# 'application' code
Logger.logr.warning('debug message')
使用
from logutil import Logger
Logger.logr.info("hello world")
标签:__,logr,log,self,path,logging,工具,python3
From: https://www.cnblogs.com/brian-sun/p/18464258