Browse Source

update: enhance logger utils

dev
dnomd343 2 years ago
parent
commit
571b3aa4d3
  1. 37
      Basis/Logger.py
  2. 19
      Decoder/Shadowsocks.py
  3. 48
      Utils/Logger.py
  4. 10
      log.py

37
Basis/Logger.py

@ -1,37 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import logging
from colorlog import ColoredFormatter
from Basis.Constant import LogLevel, LogFile
logLevel = { # log level
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL
}[LogLevel.lower()]
dateFormat = '%Y-%m-%d %H:%M:%S' # log date format
logFormat = '[%(asctime)s] [%(levelname)s] %(message)s (%(module)s.%(funcName)s)' # log format
logging.basicConfig(
level = logLevel,
format = logFormat,
datefmt = dateFormat,
filename = LogFile,
)
logHandler = logging.StreamHandler(stream = sys.stdout)
logHandler.setFormatter(ColoredFormatter(
fmt = '%(log_color)s' + logFormat,
datefmt = dateFormat,
log_colors = {
'DEBUG': 'white',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bold_red',
}
))
logging.getLogger().addHandler(logHandler)

19
Decoder/Shadowsocks.py

@ -5,19 +5,18 @@
# Plain / Common: https://shadowsocks.org/guide/configs.html#uri-and-qr-code # Plain / Common: https://shadowsocks.org/guide/configs.html#uri-and-qr-code
import copy import copy
from Basis.Logger import logging from Utils.Logger import logger
from Basis.Exception import decodeException from Basis.Exception import decodeException
from Basis.Functions import base64Decode, urlDecode from Utils.Common import urlDecode, base64Decode
ssBasicConfig = { ssBasicConfig = {
'type': 'ss', 'type': 'ss',
'info': {} 'info': {}
} }
def checkPrefix(url: str) -> str: # check url prefix and remove it def checkPrefix(url: str) -> str: # check url prefix and remove it
if not url.startswith('ss://'): if not url.startswith('ss://'):
logging.debug('Shadowsocks url should start with `ss://`') logger.debug('Shadowsocks url should start with `ss://`')
raise decodeException('Shadowsocks prefix error') raise decodeException('Shadowsocks prefix error')
return url[5:] return url[5:]
@ -39,12 +38,12 @@ def ssPlain(url: str) -> dict:
FORMAT: ss://method:password@hostname:port[#TAG] FORMAT: ss://method:password@hostname:port[#TAG]
""" """
config = copy.deepcopy(ssBasicConfig) config = copy.deepcopy(ssBasicConfig)
logging.debug('Shadowsocks plain decode -> %s' % url) logger.debug('Shadowsocks plain decode -> %s' % url)
url, config['name'] = splitTag(checkPrefix(url), False) url, config['name'] = splitTag(checkPrefix(url), False)
userinfo, url = url.rsplit('@', 1) userinfo, url = url.rsplit('@', 1)
config['info']['server'], config['info']['port'] = url.rsplit(':', 1) config['info']['server'], config['info']['port'] = url.rsplit(':', 1)
config['info']['method'], config['info']['passwd'] = userinfo.split(':', 1) config['info']['method'], config['info']['passwd'] = userinfo.split(':', 1)
logging.debug('Shadowsocks plain decode release -> %s', config) logger.debug('Shadowsocks plain decode release -> %s', config)
return config return config
@ -54,12 +53,12 @@ def ssCommon(url: str) -> dict:
base64('method:password@hostname:port') base64('method:password@hostname:port')
""" """
config = copy.deepcopy(ssBasicConfig) config = copy.deepcopy(ssBasicConfig)
logging.debug('Shadowsocks common decode -> %s' % url) logger.debug('Shadowsocks common decode -> %s' % url)
url, config['name'] = splitTag(checkPrefix(url)) url, config['name'] = splitTag(checkPrefix(url))
userinfo, url = base64Decode(url).rsplit('@', 1) userinfo, url = base64Decode(url).rsplit('@', 1)
config['info']['server'], config['info']['port'] = url.rsplit(':', 1) config['info']['server'], config['info']['port'] = url.rsplit(':', 1)
config['info']['method'], config['info']['passwd'] = userinfo.split(':', 1) config['info']['method'], config['info']['passwd'] = userinfo.split(':', 1)
logging.debug('Shadowsocks common decode release -> %s', config) logger.debug('Shadowsocks common decode release -> %s', config)
return config return config
@ -69,7 +68,7 @@ def sip002(url: str) -> dict:
userinfo => method:password or websafe-base64-encode-utf8(method:password) userinfo => method:password or websafe-base64-encode-utf8(method:password)
""" """
config = copy.deepcopy(ssBasicConfig) config = copy.deepcopy(ssBasicConfig)
logging.debug('Shadowsocks sip002 decode -> %s' % url) logger.debug('Shadowsocks sip002 decode -> %s' % url)
url, config['name'] = splitTag(checkPrefix(url)) url, config['name'] = splitTag(checkPrefix(url))
userinfo, url = url.rsplit('@', 1) userinfo, url = url.rsplit('@', 1)
try: try:
@ -86,5 +85,5 @@ def sip002(url: str) -> dict:
'param': '' if len(plugin) == 1 else plugin[1] # default as empty string 'param': '' if len(plugin) == 1 else plugin[1] # default as empty string
} }
config['info']['server'], config['info']['port'] = url.rsplit(':', 1) config['info']['server'], config['info']['port'] = url.rsplit(':', 1)
logging.debug('Shadowsocks sip002 decode release -> %s', config) logger.debug('Shadowsocks sip002 decode release -> %s', config)
return config return config

48
Utils/Logger.py

@ -0,0 +1,48 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import logging
import colorlog
from Basis.Constant import LogLevel, LogFile
logColor = { # log color
'DEBUG': 'white',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bold_red',
}
logLevel = { # log level
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL
}[LogLevel.lower()]
dateFormat = '%Y-%m-%d %H:%M:%S'
logFormat = '[%(asctime)s.%(msecs)03d] [%(levelname)s] %(message)s (%(module)s.%(funcName)s)'
# load fileHandler -> log file
fileHandler = logging.FileHandler(LogFile, encoding = 'utf-8')
fileHandler.setFormatter(logging.Formatter(
logFormat, datefmt = dateFormat
))
fileHandler.setLevel(logging.DEBUG) # debug level for log file
# load stdHandler -> stderr
stdHandler = colorlog.StreamHandler()
stdHandler.setFormatter(colorlog.ColoredFormatter(
'%(log_color)s' + logFormat,
datefmt = dateFormat,
log_colors = logColor,
stream = sys.stderr
))
stdHandler.setLevel(LogLevel) # custom level for stderr
logger = logging.getLogger()
logger.addHandler(stdHandler)
logger.addHandler(fileHandler)
logger.setLevel(logging.DEBUG) # set log level in handler

10
log.py

@ -0,0 +1,10 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from Utils.Logger import logger
logger.debug('debug')
logger.info('info')
logger.warning('warning')
logger.error('error')
logger.critical('critical')
Loading…
Cancel
Save