risotto/src/risotto/logger.py

104 lines
3.2 KiB
Python

from typing import Dict, Any
from json import dumps
from .context import Context
from .utils import _
from .config import DEBUG
class Logger:
""" An object to manager log
FIXME should add event to a database
"""
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 + ')'
print(sql, args)
if not hasattr(risotto_context, 'connection'):
if path == ' http_get message: /api/v1:':
raise Exception('pouet')
print(path)
print('MANQUE CONNEXION !!!')
print(sql)
else:
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)
paths_msg += ':'
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)
# if DEBUG:
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 DEBUG:
tmsg = _(f'{risotto_context.username}: INFO:{paths_msg}')
if arguments:
tmsg += _(f' with arguments "{arguments}"')
if msg:
tmsg += f' {msg}'
print(tmsg)
await self.insert(msg,
paths_msg,
risotto_context,
'Info',
arguments)
async def info(self,
risotto_context,
msg):
if DEBUG:
print(msg)
await self.insert(msg,
None,
risotto_context,
'Info')
log = Logger()