aboutsummaryrefslogtreecommitdiff
path: root/scripts/redis_logger.py
blob: 2ae682b5b3669880c91a80a97c7ccc17c78bc043 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
"""Utilities to log to redis for our worker scripts."""
import logging

from redis import Redis

class RedisLogger(logging.Handler):
    """Log out to redis for our worker scripts"""
    def __init__(self,#pylint: disable=[too-many-arguments]
                 rconn: Redis,
                 fullyqualifiedjobid: str,
                 messageslistname: str,
                 level:int = logging.NOTSET,
                 expiry: int = 86400):
        """Initialise the handler."""
        super().__init__(level)
        self.redisconnection = rconn
        self.jobid = fullyqualifiedjobid
        self.messageslistname = messageslistname
        self.expiry = expiry
        rconn.hset(name=fullyqualifiedjobid,
                   key="log-messagelist",
                   value=messageslistname)

    def emit(self, record):
        """Log to the messages list for a given worker."""
        self.redisconnection.rpush(self.messageslistname, self.format(record))
        self.redisconnection.expire(self.messageslistname, self.expiry)

def setup_redis_logger(rconn: Redis,
                       fullyqualifiedjobid: str,
                       job_messagelist: str,
                       expiry: int = 86400) -> RedisLogger:
    """Setup a default RedisLogger logger."""
    formatter = logging.Formatter(
                "%(asctime)s - %(name)s - %(levelname)s: %(message)s")
    rconn.hset(
        name=fullyqualifiedjobid, key="log-messagelist", value=job_messagelist)
    redislogger = RedisLogger(
        rconn, fullyqualifiedjobid, job_messagelist, expiry=expiry)
    redislogger.setFormatter(formatter)
    return redislogger