risotto/src/risotto/logger.py

87 lines
2.7 KiB
Python
Raw Normal View History

2019-12-28 12:29:11 +01:00
from typing import Dict, Any
from json import dumps
2019-11-28 16:51:56 +01:00
from .context import Context
2019-11-28 14:50:53 +01:00
from .utils import _
from .config import get_config
2019-11-28 14:50:53 +01:00
class Logger:
2019-11-28 16:51:56 +01:00
""" An object to manager log
"""
2019-12-28 12:29:11 +01:00
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)
2019-12-28 12:29:11 +01:00
2019-11-28 16:51:56 +01:00
def _get_message_paths(self,
2019-12-02 10:29:40 +01:00
risotto_context: Context):
2019-11-28 14:50:53 +01:00
paths = risotto_context.paths
2019-12-02 10:29:40 +01:00
if risotto_context.type:
paths_msg = f' {risotto_context.type} '
else:
paths_msg = ' '
2019-11-28 14:50:53 +01:00
if len(paths) == 1:
2019-12-02 10:29:40 +01:00
paths_msg += f'message: {paths[0]}'
2019-11-28 14:50:53 +01:00
else:
2019-12-02 10:29:40 +01:00
paths_msg += f'sub-messages: '
2019-11-28 14:50:53 +01:00
paths_msg += ' > '.join(paths)
return paths_msg
2019-12-28 12:29:11 +01:00
async def error_msg(self,
risotto_context: Context,
arguments,
error: str,
msg: str=''):
2019-11-28 16:51:56 +01:00
""" send message when an error append
"""
2019-12-02 10:29:40 +01:00
paths_msg = self._get_message_paths(risotto_context)
print(_(f'{risotto_context.username}: ERROR: {error} ({paths_msg} with arguments "{arguments}": {msg})'))
2019-12-28 12:29:11 +01:00
await self.insert(msg,
paths_msg,
risotto_context,
'Error',
arguments)
2019-11-28 14:50:53 +01:00
2019-12-28 12:29:11 +01:00
async def info_msg(self,
risotto_context: Context,
arguments: Dict,
msg: str=''):
2019-11-28 16:51:56 +01:00
""" send message with common information
"""
2019-11-29 09:13:16 +01:00
if risotto_context.paths:
2019-12-02 10:29:40 +01:00
paths_msg = self._get_message_paths(risotto_context)
2019-11-29 09:13:16 +01:00
else:
paths_msg = ''
if get_config()['global']['debug']:
print(_(f'{risotto_context.username}: INFO:{paths_msg}'))
2019-12-28 12:29:11 +01:00
await self.insert(msg,
paths_msg,
risotto_context,
'Info',
arguments)
2019-11-28 14:50:53 +01:00
2019-12-28 12:29:11 +01:00
async def info(self,
risotto_context,
msg):
if get_config()['global']['debug']:
2019-12-19 15:00:24 +01:00
print(msg)
2019-12-28 12:29:11 +01:00
await self.insert(msg,
2020-01-13 19:53:09 +01:00
None,
2019-12-28 12:29:11 +01:00
risotto_context,
'Info')
2019-12-19 15:00:24 +01:00
2019-11-28 14:50:53 +01:00
log = Logger()