# encoding=utf-8
import os
import time
import logging
def get_log(filepath):
logger = logging.getLogger()
formatter = logging.Formatter("%(asctime)s - %(levelname)s: %(message)s")
# %(filename)s[line:%(lineno)d]
logger.setLevel(logging.INFO)
fh = logging.FileHandler(filepath, mode='a', encoding='utf-8')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)
return logger
if __name__ == '__main__':
current_path = os.path.dirname(os.path.realpath(__file__))
logpath = os.path.join(current_path, 'log/xx_%s.log' % time.strftime('%y%m%d%H%M'))
logging = get_log(logpath)
logging.setLevel('DEBUG') # INFO DEBUG
在工具方法中打印日志,不需要多次配置,直接获取即可使用(一次配置多处可以使用)
_logger = logging.getLogger(__name__)
设置一个基础日志
log_format = '%(asctime)s - %(filename)s:%(lineno)d - %(levelname)s:%(message)s'
logging.basicConfig(filename='test.log', format=log_format, filemode='a', level=logging.DEBUG)
指定文件编码,需要改用 handlers
参数传入
logging.basicConfig(handlers=[logging.FileHandler(filename="./log_records.txt", encoding='utf-8', mode='a+')], level=logging.DEBUG)
错误记录
- 磁盘空间不足导致
Traceback (most recent call last):
File "C:\Python38\lib\logging\__init__.py", line 1085, in emit
self.flush()
File "C:\Python38\lib\logging\__init__.py", line 1065, in flush
self.stream.flush()
OSError: [Errno 28] No space left on device