Python/Logging/Thread_class.py
2024-04-19 19:24:34 +08:00

80 lines
2.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import threading
import multiprocessing as mp
from queue import Queue #Thread 無法回傳值,所以要使用 Queue.put() 將要傳回的值存入 Queue再用 Queue.get() 取出
import time
import os
import datetime
import logging
import cv2
class Thread_class(threading.Thread):
def __init__(self,code_name,logeer):
threading.Thread.__init__(self)
self.code_name = code_name
# log 設定
#self.log_setting()
self.log_setting_1()
def run(self):
print('process {} '.format(os.getpid())) # 查看進程
print('thread {} '.format(threading.current_thread().name)) # 查看線程
# log 設定
#self.log_setting_1()
#logger = self.logger
self.logger.info("Start")
for i in range(0,5):
self.logger.info(f'{self.code_name} : {i}')
time.sleep(0.5)
def test_return(self):
return(f'{self.code_name}=END')
# log setting
def log_setting(self):
day_date = (datetime.datetime.now().strftime("%Y%m%d"))
log_file = f'LOG\\Thread\\{self.code_name}-{day_date}.txt'
# 创建一个 Logger 对象
self.logger = logging.getLogger(log_file)
# 设置 Logger 级别
self.logger.setLevel(logging.INFO)
# 创建一个处理程序并将其级别设置为 INFO
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# 创建一个格式器并将其添加到处理程序
formatter = logging.Formatter('%(asctime)s - %(levelname)-8s - %(message)s', datefmt='%Y%m%d %H:%M:%S')
ch.setFormatter(formatter)
# 将处理程序添加到 logger
self.logger.addHandler(ch)
# 创建一个文件处理程序并将其添加到 logger
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(formatter)
self.logger.addHandler(file_handler)
def log_setting_1(self):
log_file = f'LOG.txt'
day_date = (datetime.datetime.now().strftime("%Y%m%d"))
log_file = f'LOG\\Thread\\{self.code_name}-{day_date}.txt'
# create logger
self.logger = logging.getLogger(log_file)
self.logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create file handler and set level to info
fh = logging.FileHandler(log_file)
fh.setLevel(logging.WARNING)
# create formatter
formatter = logging.Formatter(
'%(asctime)s - %(name)-36s - %(levelname)-8s - %(message)s')
# add formatter to console handler and file handler
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add console handler and file handler to logger
self.logger.addHandler(ch)
self.logger.addHandler(fh)