12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- # -*- coding: utf-8 -*-
- # @Time : 2021/6/7 11:02
- # @Author : XuJiakai
- # @File : log
- # @Software: PyCharm
- import logging
- import os
- import time
- import platform
- AUTO_WRITE_LOG_FILE = False if platform.system() == "Linux" else True
- AUTO_WRITE_LOG_FILE = False
- def get_log(log_name="my_log", write_file=AUTO_WRITE_LOG_FILE):
- logging.basicConfig()
- logger = logging.getLogger(log_name)
- logger.setLevel(logging.WARNING)
- # 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__':
- print(AUTO_WRITE_LOG_FILE)
- pass
|