大家好,我是Leo
今天來介紹的是logs的建立,在很多情況下我們不會時刻在電腦前面,我們必須建立logs,在問題出錯的第一時間,可以透過logs找出問題的原因
OK~~~ Let's go now!!!
階層圖如下
' |-- project
' |-- logger',
' |-- logger.py',
' |-- files'
建立一個 logger file
底下再建立兩個檔案分別為logger.py,files
from loguru import logger
import os,sys
from typing import Union
class LogManager:
__instance__ = None
show_console: bool = True
root_dir: str
loggers: list = []
ext: str = 'log'
default_level: str = 'INFO'
filename: str = '%s_{time:YYYY-MM-DD}.%s'
# root_dir 檔案路徑,這邊可以替換成自己的路徑
def __new__(cls,root_dir: str='./logger/files',show_console: bool=True, ext: str='log', default_level='INFO'):
if not LogManager.__instance__:
LogManager.__instance__ = object.__new__(cls)
checkDir = os.path.isdir(root_dir)
if not checkDir:
raise ValueError("Directory does not exist.(%s)" % root_dir)
LogManager.root_dir = root_dir
show_console = str(show_console)
if show_console is not None and show_console.lower() in ['yes', 'true', 't', '1']:
LogManager.show_console = True
else:
LogManager.show_console = False
LogManager.ext = ext
LogManager.default_level = default_level
# 刪除預設handle
logger.remove()
return LogManager.__instance__
def make_filter(self, name: str):
def filter(record):
return record["extra"].get("name") == name
return filter
def getLogger(self, name: str,
format: str='<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> {extra[name]}[<light-blue>{module}</light-blue>:{line}] <lvl>{level}</lvl> {message}',
level: Union[str, None]=None,
rotation: str='00:00',
set_root_dir: Union[str, None]=None,
set_show_console: Union[bool, None]=None):
level = level if level else self.default_level
if name not in self.loggers:
self.loggers.append(name)
logger.add(
os.path.join(
self.root_dir if not set_root_dir else set_root_dir,
self.filename % (name, self.ext),
),
format=format,
level=level,
rotation=rotation,
filter=self.make_filter(name),
)
if set_show_console is None:
if self.show_console:
logger.add(
sys.stderr,
format=format,
level=level,
filter=self.make_filter(name),
)
else:
if set_show_console:
logger.add(
sys.stderr,
format=format,
level=level,
filter=self.make_filter(name),
)
return logger.bind(name=name)
from rest_framework.response import Response
from rest_framework import permissions, views, status
from logger.logger import LogManager
logger = LogManager().getLogger('view')
class youBike(views.APIView):
permission_classes = (permissions.AllowAny,)
authentication_classes = []
def get(self,request):
try:
'''
sno(站點代號)、sna(中文場站名稱)、tot(場站總停車格)、sbi(可借車位數)、
sarea(中文場站區域)、mday(資料更新時間)、lat(緯度)、lng(經度)、
ar(中文地址)、sareaen(英文場站區域)、snaen(英文場站名稱)、aren(英文地址)、
bemp(可還空位數)、act(場站是否暫停營運)
'''
#加入log
logger.info('youbike get method strat...')
url = "https://tcgbusfs.blob.core.windows.net/dotapp/youbike/v2/youbike_immediate.json"
res = requests.get(url).json()
df = pd.DataFrame(res)[['sna','updateTime','tot','sbi','bemp','lat','lng','sarea','ar']]
key_word = request.GET.get('keyWord', None)
if key_word:
df = df[(df.sna.str.contains(key_word))|(df.ar.str.contains(key_word))|(df.sarea.str.contains(key_word))]
df.sort_values(by=['sbi','bemp'],ascending=[False,False],axis=0,inplace=True)
df.rename(columns={
'sna':'站點','updateTime':'更新時間','tot':'場站總停車格','sbi':'可借車位數','bemp':'可還空位數',
'lat':"緯度",'lng':'經度','sarea':'場站區域','ar':'地址'},inplace=True)
#加入log
logger.info('youbike get method finish...')
return Response(df.T.to_dict().values(),status=200)
except Exception as e:
#加入log
logger.error(traceback.format_exc())
return Response({'message':'error'},status=400)
敲完api後建立成功
可以點file進去裡面有logger的紀錄,以及出錯時的紀錄
今天主要介紹log檔的建立,明天來講解,如果我今天有多個api,使用api有個操作的紀錄,並存入db
我們明天見,各位掰掰~~~