1、直接上代码吧
import logging
class Logger(object):
def __init__(self, filename):
self.filename = filename
def my_log(self, msg, level):
my_logger = logging.getLogger()
my_logger.setLevel('DEBUG')
format = logging.Formatter('%(asctime)s-%(filename)s-[line:%(lineno)d]-%(name)s-%(levelname)s:%(message)s')
fh = logging.FileHandler(self.filename, encoding='utf8')
fh.setLevel('DEBUG')
fh.setFormatter(format)
my_logger.addHandler(fh)
if level == 'DEBUG':
my_logger.debug(msg)
elif level == "INFO":
my_logger.info(msg)
elif level == 'WARNING':
my_logger.warning(msg)
elif level == "ERROR":
my_logger.error(msg)
else:
my_logger.critical(msg)
my_logger.removeHandler(fh)
def debug(self, msg):
self.my_log(msg, 'DEBUG')
def error(self, msg):
self.my_log(msg, 'ERROR')
def info(self, msg):
self.my_log(msg, 'INFO')
def warning(self, msg):
self.my_log(msg, 'WARNING')
def critical(self, msg):
self.my_log(msg, 'CRITICAL')
if __name__ == '__main__':
log = Logger('mylog.log')
log.debug('hello')
log.info('world')
2、输出如下
2021-05-11 15:35:25,420-get_log.py-[line:15]-root-DEBUG:hello
2021-05-11 15:35:52,359-get_log.py-[line:15]-root-INFO:world
3、在其他文件直接引入调用即可
from get_log import Logger
log=Logger('mylog.log')#实例化一个对象,目前只需要输入日志路径即可
log.info('hello')
log.debug('wold')