loging
python-log的使用,本代码可直接运行,外部直接调用即可,在日常使用过程中直接复制黏贴即可
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:zhj
import logging, os
from logging import handlers
class Logger():
def __init__(self, log_filename="info.log",path="/Logs", when='midnight', back_count=0,level=logging.DEBUG):
self.logger = logging.getLogger(log_filename)
self.logger.setLevel(level)
parent_dir = os.path.dirname(os.path.realpath(__file__))
self.log_path = os.path.join(parent_dir+path)
print(self.log_path)
if not os.path.exists(self.log_path):
os.mkdir(self.log_path)
self.log_file_path = os.path.join(self.log_path, log_filename)
# print(self.log_file_path)
#formatter = logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s') # 备用
formatter = logging.Formatter('%(asctime)s - %(levelname)s: %(message)s')
# self.logger = logging.getLogger(path)
# self.logger.setLevel(logging.DEBUG)
#fmt = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
# 1设置CMD日志
sh = logging.StreamHandler()
sh.setLevel(level)
sh.setFormatter(formatter)
# 2设置info文件日志
fh = logging.handlers.TimedRotatingFileHandler(filename=self.log_file_path,when=when,backupCount=back_count,encoding='utf-8')
fh.setLevel(level)
# 设置日志输出格式
fh.setFormatter(formatter)
# 3设置error文件日志
gf = logging.handlers.TimedRotatingFileHandler(filename=self.log_path+"error.log", when=when,backupCount=back_count,encoding='utf-8')
gf.setLevel(logging.ERROR)
gf.setFormatter(formatter)
# 添加到logger对象里
self.logger.addHandler(fh)
self.logger.addHandler(sh)
self.logger.addHandler(gf)
# fh = logging.FileHandler(path)
# fh.setFormatter(fmt)
# fh.setLevel(Flevel)
# self.logger.addHandler(sh)
# self.logger.addHandler(fh)
def debug(self, message):
self.logger.debug(message)
def info(self, message):
self.logger.info(message)
def war(self, message):
self.logger.warning(message)
def error(self, message):
self.logger.error(message)
def cri(self, message):
self.logger.critical(message)
if __name__ == '__main__':
logyyx = Logger(log_filename="info.log")
logyyx.debug('一个debug信息')
logyyx.info('一个info信息')
logyyx.war('一个warning信息')
logyyx.error('一个error信息')
logyyx.cri('一个致命critical信息')