import logging
def writ2log(log_dir,log_files_name):
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# 创建一个FileHandler,用于写入日志文件
log_file = '{0}{1}.log'.format(log_dir,log_files_name)
fh = logging.FileHandler(log_file, mode='a',encoding='utf-8')
fh.setLevel(logging.DEBUG)
# 创建一个StreamHandler,用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# 定义日志格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# 添加两个Handler
logger.addHandler(fh)
logger.addHandler(ch)
return logger
if __name__ == '__main__':
logger=writ2log("./logs/","newlogs")
logger.debug('This is a debug message.')
logger.info('This is an info message.')
logger.warning('This is a warning message.')
logger.error('This is an error message.')
logger.critical('This is a 哈哈哈哈哈critical message.')
输出效果