molior-dbs/molior

Improve logging by showing logged in user that triggers an API

lbolla opened this issue · 3 comments

When debugging, it's useful to know which API calls are triggered manually by logged in users.

@neolynx What do you think of changing cirrina logging format to emit something like this?

Oct 05 13:21:37 molior-test molior[50645]: [admin] 127.0.0.1 GET /api/status 200 in 0.007639s
Oct 05 13:21:38 molior-test molior[50645]: [admin] 127.0.0.1 GET /api/users 200 in 0.004822s
Oct 05 13:21:38 molior-test molior[50645]: [admin] 127.0.0.1 GET /api/nodes 200 in 0.001323s
Oct 05 13:21:39 molior-test molior[50645]: [admin] 127.0.0.1 GET /api2/repositories 200 in 0.005186s
Oct 05 13:21:39 molior-test molior[50645]: [admin] 127.0.0.1 GET /api/mirror 200 in 0.038432s

Note the "[admin]" logged in user.

The code to do that would be something like:

from aiohttp.abc import AbstractAccessLogger 
 
class AccessLogger(AbstractAccessLogger): 
 
    def _get_username(self, request): 
        try: 
            return request.cirrina.web_session.get('username') 
        except Exception: 
            return None 
 
    def log(self, request, response, time): 
        username = self._get_username(request) 
        self.logger.info( 
                f'[{username}] ' 
                f'{request.remote} ' 
                f'{request.method} {request.path} {response.status} ' 
                f'in {time:.6f}s') 

and then use it as:

       self.srv = await self.loop.create_server(
            self.app.make_handler(
                access_log_class=AccessLogger,
                access_log_format='%r %s',
                access_log=self.logger,
                logger=self.logger),

We could also improve cirrina to accept an access_log_class and pass it in from Molior.

I've submitted a PR to cirrina to enable such loggers.
neolynx/cirrina#33

PR submitted: #34

Please review!