Python/Logging/Process_class.py

80 lines
2.8 KiB
Python
Raw Normal View History

2024-04-19 19:24:34 +08:00
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 Process_class(mp.Process):
def __init__(self, code_name,q):
mp.Process.__init__(self)
self.code_name = code_name
# log 設定
#self.log_setting()
self.q = q
#self.log_setting_1()
def run(self):
self.t = self.code_name
self.q.put(self.t)
print('process {} '.format(os.getpid())) # 查看進程
print('thread {} '.format(threading.current_thread().name)) # 查看線程
# log 設定
self.log_setting()
self.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.q.get_nowait())}=END')
# log setting
def log_setting(self):
day_date = (datetime.datetime.now().strftime("%Y%m%d"))
log_file = f'LOG\\Process\\{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'
# 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.INFO)
# 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)