apppublic/appPublic/app_logger.py

89 lines
1.9 KiB
Python
Raw Normal View History

2024-07-09 18:25:04 +08:00
import os
2022-03-23 12:24:04 +08:00
import sys
import logging
from functools import partial
2024-07-09 18:25:04 +08:00
from appPublic.timeUtils import timestampstr
2022-03-23 12:24:04 +08:00
levels={
"debug":logging.DEBUG,
"info":logging.INFO,
"warning":logging.WARNING,
"error":logging.error,
"critical":logging.CRITICAL
}
2022-04-06 14:05:35 +08:00
defaultfmt = '%(asctime)s[%(name)s][%(levelname)s][%(filename)s:%(lineno)s]%(message)s'
2022-03-25 20:44:26 +08:00
logfile = -1
logger = None
2022-06-23 16:37:46 +08:00
g_levelname='info'
2022-04-06 14:05:35 +08:00
level = levels.get('info')
2022-03-23 12:24:04 +08:00
2023-06-08 11:22:58 +08:00
def create_logger(name, formater=defaultfmt, levelname=None, file=None):
global logger, logfile, level, g_levelname
2022-03-25 20:44:26 +08:00
if logfile == -1:
logfile = file
if logger:
return logger
logger = logging.getLogger(name)
2023-06-08 11:22:58 +08:00
if levelname:
g_levelname = levelname
else:
levelname = g_levelname
2022-04-06 14:05:35 +08:00
level = levels.get(levelname, levels.get('info'))
logger.setLevel(level)
2022-03-23 12:24:04 +08:00
format = logging.Formatter(formater)
file_handler = None
2022-03-25 20:44:26 +08:00
if logfile is not None:
file_handler = logging.FileHandler(logfile)
2022-03-23 12:24:04 +08:00
else:
file_handler = logging.StreamHandler()
file_handler.setFormatter(format)
logger.addHandler(file_handler)
return logger
2022-03-25 20:44:26 +08:00
2024-07-10 13:47:45 +08:00
2024-07-09 18:25:04 +08:00
def info(*args, **kw):
global logger
if logger is None:
return
logger.info(*args, **kw)
def debug(*args, **kw):
global logger
if logger is None:
return
logger.debug(*args, **kw)
def warning(*args, **kw):
global logger
if logger is None:
return
logger.warning(*aegs, **kw)
def error(*args, **kw):
global logger
if logger is None:
return
logger.error(*args, **kw)
def critical(*args, **kw):
global logger
if logger is None:
return
logger.critical(*args, **kw)
def exception(*args, **kw):
global logger
if logger is None:
return
logger.exception(**args, **kw)
2022-03-25 20:44:26 +08:00
class AppLogger:
def __init__(self):
self.logger = create_logger(self.__class__.__name__)
self.debug = self.logger.debug
self.info = self.logger.info
self.warning = self.logger.warning
self.error = self.logger.error
self.critical = self.logger.critical
self.exception = self.logger.exception