import os
import random
import sys
import multiprocessing
import time
from shutil import copyfile
from colorlog import ColoredFormatter
log directory
LOG_DIR = “./logs”
level fot stdout
STD_LEVEL = logging.WARN
level for file
FILE_LEVEL = logging.DEBUG
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
class Log:
def init(self, log_dir=LOG_DIR):
“”"
function:init create log file, judge if log file is too bigger
:param log_dir: directory of logs
“”"
log_path = log_dir + “/log”
if not os.path.exists(log_dir):
os.mkdir(log_dir)
os.chmod(log_dir, 0o777)
if not os.path.exists(log_path):
f = open(log_path, mode=‘w’, encoding=‘utf-8’)
f.close()
os.chmod(log_path, 0o777)
# if log file is more than 1MB, copy to a file and clear log file
if os.path.getsize(log_path) / 1048576 > 1:
# print(os.path.getsize(log_path))
copyfile(log_path, log_dir + “/log” + str(time.time()).replace(“.”, “”))
with open(log_path, ‘w’) as f:
f.truncate()
f.close()
self.logger_format = logging.Formatter(‘%(asctime)s - %(levelname)s: %(message)s’)
self.c_logger_format = ColoredFormatter(fmt=‘%(log_color)s%(asctime)s’
’ - %(log_color)s%(levelname)s: %(log_color)s%(message)s’,
reset=True,
secondary_log_colors={},
style=‘%’
)
self.logger = logging.getLogger(str(random.random()))
self.logger.handlers.clear()
self.logger.setLevel(logging.DEBUG)
self.filehandler = logging.FileHandler(log_path, mode='a')
self.filehandler.setLevel(FILE_LEVEL)
self.filehandler.setFormatter(self.logger_format)
self.stdouthandler &