1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- # -*- coding: utf-8 -*-
- # @Time : 2021/6/7 11:02
- # @Author : XuJiakai
- # @File : log
- # @Software: PyCharm
- import logging
- import os
- import time
- def get_log(log_name="my_log", write_file=False):
- logging.basicConfig()
- logger = logging.getLogger(log_name)
- logger.setLevel(logging.INFO)
- logger.propagate = False
- # 日志输出格式
- formatter = logging.Formatter('[%(asctime)s - ' + log_name + ':%(lineno)d] - %(levelname)s: %(message)s')
- if write_file:
- # 创建logs文件夹
- cur_path = os.path.dirname(os.path.realpath(__file__))
- log_path = os.path.join(cur_path, 'logs')
- # 如果不存在这个logs文件夹,就自动创建一个
- if not os.path.exists(log_path):
- os.mkdir(log_path)
- log_name = os.path.join(log_path, '%s.log' % time.strftime('%Y_%m_%d'))
- fh = logging.FileHandler(log_name, 'a', encoding='utf-8') # 这个是python3的
- # 创建一个FileHandler,用于写到本地
- fh.setLevel(logging.INFO)
- fh.setFormatter(formatter)
- logger.addHandler(fh)
- # 创建一个StreamHandler,用于输出到控制台
- ch = logging.StreamHandler()
- ch.setLevel(logging.INFO)
- ch.setFormatter(formatter)
- logger.addHandler(ch)
- return logger
- if __name__ == '__main__':
- pass
|