Best Python code snippet using localstack_python
utils.py
Source:utils.py
...12mod_logger = logging.getLogger('log_mod')13class ViewDecorate(object):14 @classmethod15 def record_view_exception(cls, func):16 def record_exception(*args, **kwargs):17 beg_time = datetime.now()18 try:19 back = func(*args, **kwargs)20 end_time = datetime.now()21 time_dtt = str((end_time - beg_time).total_seconds())22 view_logger.info('func: %s, cost:%s s' % (func.__name__, time_dtt))23 return back24 except Exception, e:25 end_time = datetime.now()26 time_dtt = str((end_time - beg_time).total_seconds())27 view_logger.warning('func: %s, cost:%s s, error:%s' % (func.__name__, time_dtt,28 traceback.format_exc()+'\n'+str(e)))29 return render_template('common/file_500.html',30 err='func: %s, cost:%s s, error:%s' %31 (func.__name__, time_dtt, traceback.format_exc()+'\n'+str(e)))32 return record_exception33 @classmethod34 def record_call_exception(cls, func):35 def record_exception(*args, **kwargs):36 beg_time = datetime.now()37 try:38 back = func(*args, **kwargs)39 end_time = datetime.now()40 time_dtt = str((end_time - beg_time).total_seconds())41 view_logger.info('func: %s, cost:%s s' % (func.__name__, time_dtt))42 return back43 except Exception, e:44 end_time = datetime.now()45 time_dtt = str((end_time - beg_time).total_seconds())46 view_logger.warning('func: %s, cost:%s s, error:%s' % (func.__name__, time_dtt,47 traceback.format_exc()+'\n'+str(e)))48 return jsonify({'resCode': 500, 'data': None, 'mess': traceback.format_exc()+'\n'+str(e)})49 return record_exception50class DBDecorate(object):51 @classmethod52 def record_db_exception(cls, func):53 def record_exception(*args, **kwargs):54 beg_time = datetime.now()55 try:56 back = func(*args, **kwargs)57 end_time = datetime.now()58 time_dtt = str((end_time - beg_time).total_seconds())59 db_logger.debug('func: %s, cost:%s s' % (func.__name__, time_dtt))60 return back61 except Exception, e:62 end_time = datetime.now()63 time_dtt = str((end_time - beg_time).total_seconds())64 db_logger.warning('func: %s, cost:%s s, error:%s' % (func.__name__, time_dtt,65 traceback.format_exc()+'\n'+str(e)))66 return list()67 return record_exception68 @classmethod69 def record_updates_exception(cls, func):70 def record_exception(*args, **kwargs):71 beg_time = datetime.now()72 try:73 back = func(*args, **kwargs)74 end_time = datetime.now()75 time_dtt = str((end_time - beg_time).total_seconds())76 db_logger.debug('func: %s, cost:%s s' % (func.__name__, time_dtt))77 return back78 except Exception, e:79 end_time = datetime.now()80 time_dtt = str((end_time - beg_time).total_seconds())81 db_logger.warning('func: %s, cost:%s s, error:%s' % (func.__name__, time_dtt,82 traceback.format_exc()+'\n'+str(e)))83 return 084 return record_exception85class ModDecorate(object):86 @classmethod87 def record_mod_exception(cls, func):88 def record_exception(*args, **kwargs):89 beg_time = datetime.now()90 try:91 back = func(*args, **kwargs)92 end_time = datetime.now()93 time_dtt = str((end_time - beg_time).total_seconds())94 mod_logger.debug('func: %s, cost:%s s' % (func.__name__, time_dtt))95 return back96 except Exception, e:97 end_time = datetime.now()98 time_dtt = str((end_time - beg_time).total_seconds())99 mod_logger.warning('func: %s, cost:%s s, error:%s' % (func.__name__, time_dtt,100 traceback.format_exc()+'\n'+str(e)))101 return list()102 return record_exception103class AppDecorate(object):104 @classmethod105 def record_app_exception(cls, func):106 def record_exception(*args, **kwargs):107 beg_time = datetime.now()108 try:109 back = func(*args, **kwargs)110 end_time = datetime.now()111 time_dtt = str((end_time - beg_time).total_seconds())112 app_logger.debug('func: %s, cost:%s s' % (func.__name__, time_dtt))113 return back114 except Exception, e:115 end_time = datetime.now()116 time_dtt = str((end_time - beg_time).total_seconds())117 app_logger.warning('func: %s, cost:%s s, error:%s' % (func.__name__, time_dtt,118 traceback.format_exc()+'\n'+str(e)))119 return {'resCode': 500, 'data': None, 'mess': traceback.format_exc()+'\n'+str(e)}120 return record_exception...
logging.py
Source:logging.py
1from __future__ import annotations2import sys3import logging4import loguru5from loguru import logger6from typing import Union7from {{cookiecutter.project_slug}}.types import BaseError8from {{cookiecutter.project_slug}}.config import Configuration9class InterceptLoguruHandler(logging.Handler):10 def __init__(self, stream: str = ""):11 del stream12 super().__init__()13 def emit(self, record: logging.LogRecord) -> None:14 # Get corresponding Loguru level if it exists15 try:16 level: Union[str, int] = logger.level(record.levelname).name17 except ValueError:18 level = record.levelno19 # Find caller from where originated the logged message20 frame, depth = logging.currentframe(), 221 while frame.f_code.co_filename == logging.__file__:22 frame = frame.f_back # type: ignore23 depth += 124 logger.opt(depth=depth, exception=record.exc_info).log(25 level, record.getMessage()26 )27def exception_patcher(record: loguru.Record) -> None:28 record_exception = record["exception"]29 if (30 record_exception31 and record_exception.value32 and isinstance(record_exception.value, BaseError)33 ):34 record["extra"]["error_code"] = record_exception.value.code35 record["extra"]["error_message"] = record_exception.value.message36def setup_logging(config: Configuration) -> None:37 logging.basicConfig(handlers=[InterceptLoguruHandler()], level=0)38 if config.debug:39 logger.configure(40 handlers=[41 {42 "sink": sys.stdout,43 "level": "INFO",44 "format": (45 "<green>{time:YYYY-MM-DDTHH:mm:ss.SSS}</green> | <level>{level: <8}</level> | "46 " <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level> | "47 "<level>{extra!s}</level>"48 ),49 "enqueue": True,50 },51 ],52 patcher=exception_patcher,53 )54 else:55 logger.configure(56 handlers=[57 {58 "sink": sys.stdout,59 "serialize": True,60 "colorize": False,61 "level": "INFO",62 "enqueue": True,63 "backtrace": False,64 }65 ],66 patcher=exception_patcher,...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!