- 线程1的日志输出在 Thread-1.log
- 线程2的日志输出在 Thread-2.log
import threading
import logging
log_lock = threading.Lock()
_log_dict = dict()
def log(msg):
with log_lock:
thread_name = threading.currentThread().getName()
if thread_name in _log_dict:
logger = _log_dict[thread_name]
else:
logger = logging.getLogger(thread_name)
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler(f'{thread_name}.log', mode='w', encoding='utf-8')
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
_log_dict[thread_name] = logger
logger.info(str(msg))
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
for i in range(5):
t = threading.Thread(target=log, args=(i,))
t.start()