项目文件夹

文件

项目文件夹

0
T

86 行
2.4 KiB
Python

2021-02-25 15:53:35 +08:00
import logging
import os
2022-10-08 11:59:37 +08:00
import time
2021-02-25 15:53:35 +08:00
def _transform_log_level(str_level):
2022-10-08 11:59:37 +08:00
if str_level == "info":
2021-02-25 15:53:35 +08:00
return logging.INFO
2022-10-08 11:59:37 +08:00
elif str_level == "warning":
2021-02-25 15:53:35 +08:00
return logging.WARNING
2022-10-08 11:59:37 +08:00
elif str_level == "critical":
2021-02-25 15:53:35 +08:00
return logging.CRITICAL
2022-10-08 11:59:37 +08:00
elif str_level == "debug":
2021-02-25 15:53:35 +08:00
return logging.DEBUG
2022-10-08 11:59:37 +08:00
elif str_level == "error":
2021-02-25 15:53:35 +08:00
return logging.ERROR
else:
2022-10-08 11:59:37 +08:00
raise KeyError("Log level error")
2021-02-25 15:53:35 +08:00
class LightLogging(object):
2022-10-08 11:59:37 +08:00
def __init__(self, log_path=None, log_name="lightlog", log_level="debug"):
2021-02-25 15:53:35 +08:00
log_level = _transform_log_level(log_level)
if log_path:
2022-10-08 11:59:37 +08:00
if not log_path.endswith("/"):
log_path += "/"
2021-02-25 15:53:35 +08:00
if not os.path.exists(log_path):
os.mkdir(log_path)
2022-10-08 11:59:37 +08:00
if log_name.endswith("-") or log_name.endswith("_"):
log_name = (
log_path
+ log_name
+ time.strftime(
"%Y-%m-%d-%H:%M", time.localtime(time.time())
)
+ ".log"
)
2021-02-25 15:53:35 +08:00
else:
2022-10-08 11:59:37 +08:00
log_name = (
log_path
+ log_name
+ "_"
+ time.strftime(
"%Y-%m-%d-%H-%M", time.localtime(time.time())
)
+ ".log"
)
2021-02-25 15:53:35 +08:00
2022-10-08 11:59:37 +08:00
logging.basicConfig(
level=log_level,
format="%(asctime)s %(levelname)s: %(message)s",
datefmt="%Y-%m-%d-%H:%M",
handlers=[
logging.FileHandler(log_name, mode="w"),
logging.StreamHandler(),
],
)
logging.info("Start Logging")
logging.info("Log file path: {}".format(log_name))
2021-02-25 15:53:35 +08:00
else:
2022-10-08 11:59:37 +08:00
logging.basicConfig(
level=log_level,
format="%(asctime)s %(levelname)s: %(message)s",
datefmt="%Y-%m-%d-%H:%M",
handlers=[logging.StreamHandler()],
)
logging.info("Start Logging")
2021-02-25 15:53:35 +08:00
def debug(self, msg):
logging.debug(msg)
def info(self, msg):
logging.info(msg)
def critical(self, msg):
logging.critical(msg)
def warning(self, msg):
logging.warning(msg)
def error(self, msg):
2022-10-08 11:59:37 +08:00
logging.error(msg)