87 lines
2.7 KiB
Python
87 lines
2.7 KiB
Python
from typing import Dict, Any
|
|
from json import dumps
|
|
from .context import Context
|
|
from .utils import _
|
|
from .config import get_config
|
|
|
|
|
|
class Logger:
|
|
""" An object to manager log
|
|
"""
|
|
async def insert(self,
|
|
msg: str,
|
|
path: str,
|
|
risotto_context: str,
|
|
level: str,
|
|
data: Any= None) -> None:
|
|
insert = 'INSERT INTO log(Msg, Path, Username, Level'
|
|
values = 'VALUES($1,$2,$3,$4'
|
|
args = [msg, path, risotto_context.username, level]
|
|
if data:
|
|
insert += ', Data'
|
|
values += ',$5'
|
|
args.append(dumps(data))
|
|
|
|
sql = insert + ') ' + values + ')'
|
|
await risotto_context.connection.fetch(sql, *args)
|
|
|
|
def _get_message_paths(self,
|
|
risotto_context: Context):
|
|
paths = risotto_context.paths
|
|
if risotto_context.type:
|
|
paths_msg = f' {risotto_context.type} '
|
|
else:
|
|
paths_msg = ' '
|
|
if len(paths) == 1:
|
|
paths_msg += f'message: {paths[0]}'
|
|
else:
|
|
paths_msg += f'sub-messages: '
|
|
paths_msg += ' > '.join(paths)
|
|
return paths_msg
|
|
|
|
async def error_msg(self,
|
|
risotto_context: Context,
|
|
arguments,
|
|
error: str,
|
|
msg: str=''):
|
|
""" send message when an error append
|
|
"""
|
|
paths_msg = self._get_message_paths(risotto_context)
|
|
print(_(f'{risotto_context.username}: ERROR: {error} ({paths_msg} with arguments "{arguments}": {msg})'))
|
|
await self.insert(msg,
|
|
paths_msg,
|
|
risotto_context,
|
|
'Error',
|
|
arguments)
|
|
|
|
async def info_msg(self,
|
|
risotto_context: Context,
|
|
arguments: Dict,
|
|
msg: str=''):
|
|
""" send message with common information
|
|
"""
|
|
if risotto_context.paths:
|
|
paths_msg = self._get_message_paths(risotto_context)
|
|
else:
|
|
paths_msg = ''
|
|
if get_config()['global']['debug']:
|
|
print(_(f'{risotto_context.username}: INFO:{paths_msg}'))
|
|
await self.insert(msg,
|
|
paths_msg,
|
|
risotto_context,
|
|
'Info',
|
|
arguments)
|
|
|
|
async def info(self,
|
|
risotto_context,
|
|
msg):
|
|
if get_config()['global']['debug']:
|
|
print(msg)
|
|
await self.insert(msg,
|
|
None,
|
|
risotto_context,
|
|
'Info')
|
|
|
|
|
|
log = Logger()
|