Ticket #6970: pyth.mythlog.patch

File pyth.mythlog.patch, 14.2 KB (added by Raymond Wagner <raymond@…>, 15 years ago)
  • MythTV/MythVideo.py

     
    3535                try:
    3636                        cur.execute(u"select * from storagegroup")
    3737                except MySQLdb.Error, e:
    38                         log.Msg(INFO, u"! Error: Reading storagegroup MythTV table: %d: %s\n" % (e.args[0], e.args[1]))
    3938                        return None
    4039
    4140                videos_dir = []
     
    102101                                if os.path.exists(filename): # Handle multiple Videos SGs for one backend
    103102                                        break
    104103                        else:
    105                                 log.Msg(INFO, u'%s not exist, removing metadata...', filename)
     104                                log.info('Videometadata',u'%s not exist, removing metadata...'% filename)
    106105                                rmMetadata(intid)
    107106                c.close()
    108107
     
    322321                        c.close()
    323322                        return intid
    324323                else:
    325                         log.Msg(DEBUG, 'Updating metadata for %s', id)
     324                        log.debug('Videometadata', 'Updating metadata for %s' % id)
    326325                        format_string = ', '.join(['%s = %%s' % d for d in data])
    327326                        sql = "UPDATE videometadata SET %s WHERE intid = %%s" % format_string
    328327                        sql_values = data.values()
     
    341340                c = self.db.cursor()
    342341                if isinstance(video, str):
    343342                        if video[0] !='/' and host == None: # Protect against accidental multiple deletions on SG's
    344                                 log.Msg(WARNING, u"Attempting to delete a video for a storage group when the hostname is not supplied. That could potentially remove the videometadata on multiple backends " +
     343                                log.warning('Metadata delete', u"Attempting to delete a video for a storage group when the hostname is not supplied. That could potentially remove the videometadata on multiple backends " +
    345344                                                u"for videometadata: %s" % video)
    346345                                return
    347346                        intid = self.getMetadataId(video, host)
    348347                        if intid == None:
    349                                 log.Msg(WARNING, u"Attempt to delete a video that does not exist " +
     348                                log.warning('Metadata delete', u"Attempt to delete a video that does not exist " +
    350349                                                u"for videometadata: %s" % video)
    351350                                return
    352351                        c.execute("DELETE FROM videometadata WHERE intid = %s", (intid,))
     
    354353                elif isinstance(video, int) or isinstance(video, long):
    355354                        c.execute("DELETE FROM videometadata WHERE intid = %s", (video,))
    356355                else:
    357                         log.Msg(WARNING, "Attempt to delete non-str, non-int item" +
     356                        log.warning('Metadata delete', "Attempt to delete non-str, non-int item" +
    358357                                        "from videometadata: %s" % str(video))
    359358                # Clean up this video's relationships to Genres, Country and Cast
    360359                self.cleanGenres(video)
  • MythTV/MythTV.py

     
    2020from MythDB import *
    2121from MythLog import *
    2222
    23 log = MythLog(CRITICAL, '#%(levelname)s - %(message)s', 'MythTV')
     23log = MythLog(CRITICAL, 'MythTV.py')
    2424
    2525RECSTATUS = {
    2626                'TunerBusy': -8,
     
    5959                self.master_port = int(self.db.getSetting('MasterServerPort'))
    6060
    6161                if not self.master_host:
    62                         log.Msg(CRITICAL, 'Unable to find MasterServerIP in database')
     62                        log.critical('Settings','Unable to find MasterServerIP in database')
    6363                        sys.exit(1)
    6464                if not self.master_port:
    65                         log.Msg(CRITICAL, 'Unable to find MasterServerPort in database')
     65                        log.critical('Settings','Unable to find MasterServerPort in database')
    6666                        sys.exit(1)
    6767
    6868                try:
     
    7171                        self.socket.connect((self.master_host, self.master_port))
    7272                        res = self.backendCommand('MYTH_PROTO_VERSION %s' % PROTO_VERSION).split(BACKEND_SEP)
    7373                        if res[0] == 'REJECT':
    74                                 log.Msg(CRITICAL, 'Backend has version %s and we speak version %s', res[1], PROTO_VERSION)
     74                                log.critical('Protocol Mismatch',"Backend has version %s and we speak version %s" % (res[1], PROTO_VERSION))
    7575                                sys.exit(1)
    7676                        res = self.backendCommand('ANN %s %s 0' % (conn_type, socket.gethostname()))
    7777                        if res != 'OK':
    78                                 log.Msg(CRITICAL, 'Unexpected answer to ANN command: %s', res)
     78                                log.critical('Protocol Error',"Unexpected answer to ANN command: %s" % res)
    7979                        else:
    80                                 log.Msg(INFO, 'Successfully connected mythbackend at %s:%d', self.master_host, self.master_port)
     80                                log.info('Info',"Successfully connected mythbackend at %s:%d" % (self.master_host, self.master_port))
    8181                except socket.error, e:
    82                         log.Msg(CRITICAL, 'Couldn\'t connect to %s:%d (is the backend running)', self.master_host, self.master_port)
     82                        log.critical('Protocol Error',"Couldn't connect to %s:%d (is the backend running)" % (self.master_host, self.master_port))
    8383                        sys.exit(1)
    8484
    8585        def __del__(self):
     
    114114                                return u''.join(data)
    115115
    116116                command = u'%-8d%s' % (len(data), data)
    117                 log.Msg(DEBUG, 'Sending command: %s', command)
     117                log.debug('Info','Sending command: %s' % command)
    118118                self.socket.send(command)
    119119                return recv()
    120120
     
    126126                res = self.backendCommand('QUERY_GETALLPENDING').split(BACKEND_SEP)
    127127                has_conflict = int(res.pop(0))
    128128                num_progs = int(res.pop(0))
    129                 log.Msg(DEBUG, '%s pending recordings', num_progs)
     129                log.debug('Info','%s pending recordings' % num_progs)
    130130                for i in range(num_progs):
    131131                        programs.append(Program(res[i * PROGRAM_FIELDS:(i * PROGRAM_FIELDS)
    132132                                + PROGRAM_FIELDS]))
     
    139139                programs = []
    140140                res = self.backendCommand('QUERY_GETALLSCHEDULED').split(BACKEND_SEP)
    141141                num_progs = int(res.pop(0))
    142                 log.Msg(DEBUG, '%s scheduled recordings', num_progs)
     142                log.debug('Info','%s scheduled recordings' % num_progs)
    143143                for i in range(num_progs):
    144144                        programs.append(Program(res[i * PROGRAM_FIELDS:(i * PROGRAM_FIELDS)
    145145                                + PROGRAM_FIELDS]))
     
    247247                programs = []
    248248                res = self.backendCommand('QUERY_RECORDINGS Play').split('[]:[]')
    249249                num_progs = int(res.pop(0))
    250                 log.Msg(DEBUG, '%s total recordings', num_progs)
     250                log.debug('Info','%s total recordings' % num_progs)
    251251                for i in range(num_progs):
    252252                        programs.append(Program(res[i * PROGRAM_FIELDS:(i * PROGRAM_FIELDS)
    253253                                + PROGRAM_FIELDS]))
     
    414414                elif mode == 'w':
    415415                        write = 1
    416416                else:
    417                         log.Msg(CRITICAL, 'Invalid FileTransfer mode given')
     417                        log.critical('Filetransfer', 'Invalid FileTransfer mode given')
    418418                        sys.exit(1)
    419419                if isinstance(file, Program):
    420420                        match = regex.match(file.filename)
     
    426426                                self.port = 6543
    427427                elif isinstance(file, tuple):
    428428                        if len(file) != 3:
    429                                 log.Msg(CRITICAL, 'Incorrect FileTransfer() input size')
     429                                log.critical('Filetransfer', 'Incorrect FileTransfer() input size')
    430430                                sys.exit(1)
    431431                        else:
    432432                                self.host = file[0]
     
    436436                elif isinstance(file, str):
    437437                        match = regex.match(file)
    438438                        if match is None:
    439                                 log.Msg(CRITICAL, 'Incorrect FileTransfer() input string: %s' % file)
     439                                log.critical('Filetransfer', 'Incorrect FileTransfer() input string: %s' % file)
    440440                                sys.exit(1)
    441441                        self.sgroup = match.group('group')
    442442                        self.host = match.group('host')
     
    447447                        if self.port is None:
    448448                                self.port = 6543
    449449                else:
    450                         log.Msg(CRITICAL, 'Improper input to FileTransfer()')
     450                        log.critical('Filetransfer', 'Improper input to FileTransfer()')
    451451                        sys.exit(1)
    452452
    453453                try:
     
    456456                        self.datsock.connect((self.host, self.port))
    457457                        res = self.send('MYTH_PROTO_VERSION %s' % PROTO_VERSION).split(BACKEND_SEP)
    458458                        if res[0] == 'REJECT':
    459                                 log.Msg(CRITICAL, 'Backend has version %s and we speak version %s', res[1], PROTO_VERSION)
     459                                log.critical('Filetransfer', 'Backend has version %s and we speak version %s' % (res[1], PROTO_VERSION))
    460460                                sys.exit(1)
    461461                        res = self.send('ANN FileTransfer %s %d %d %d%s%s%s%s' % (socket.gethostname(), write, False, -1, BACKEND_SEP, self.filename, BACKEND_SEP, self.sgroup))
    462462                        if res.split(BACKEND_SEP)[0] != 'OK':
    463                                 log.Msg(CRITICAL, 'Unexpected answer to ANN command: %s', res)
     463                                log.critical('Filetransfer', 'Unexpected answer to ANN command: %s' % res)
    464464                        else:
    465                                 log.Msg(INFO, 'Successfully connected mythbackend at %s:%d', self.host, self.port)
     465                                log.info('Filetransfer', 'Successfully connected mythbackend at %s:%d' % (self.host, self.port))
    466466                                sp = res.split(BACKEND_SEP)
    467467                                self.sockno = int(sp[1])
    468468                                self.pos = 0
    469469                                self.size = (int(sp[2]) + (int(sp[3])<0))*2**32 + int(sp[3])
    470470                               
    471471                except socket.error, e:
    472                         log.Msg(CRITICAL, 'Couldn\'t connect to %s:%d (is the backend running)', self.host, self.port)
     472                        log.critical('Filetransfer', "Couldn't connect to %s:%d (is the backend running)" % (self.host, self.port))
    473473                        sys.exit(1)
    474474
    475475        def __del__(self):
     
    481481
    482482        def send(self,data):
    483483                command = '%-8d%s' % (len(data), data)
    484                 log.Msg(DEBUG, 'Sending command: %s', command)
     484                log.debug('Filetransfer', 'Sending command: %s' % command)
    485485                self.datsock.send(command)
    486486                return self.recv()
    487487
     
    588588                        if offset < -self.size:
    589589                                offset = -self.size
    590590                else:
    591                         log.Msg(CRITICAL, 'Whence can only be 0, 1, or 2')
     591                        log.critical('Filetransfer', 'Whence can only be 0, 1, or 2')
    592592
    593593                curhigh,curlow = self.comsock.splitInt(self.pos)
    594594                offhigh,offlow = self.comsock.splitInt(offset)
  • MythTV/MythLog.py

     
    22Provides simple logging and exception classes.
    33"""
    44
    5 import logging
     5from MythDB import *
     6from socket import gethostname
     7from datetime import datetime
     8from sys import version_info
    69
     10db = MythDB()
     11
    712# Vars to imporove readability
    8 CRITICAL = logging.CRITICAL
    9 FATAL = logging.FATAL
    10 ERROR = logging.ERROR
    11 WARNING = logging.WARNING
    12 INFO = logging.INFO
    13 DEBUG = logging.DEBUG
     13ALL = 8
     14DEBUG = 7
     15INFO = 6
     16NOTICE = 5
     17WARNING = 4
     18ERROR = 3
     19CRITICAL = 2
     20ALERT = 1
     21EMERGENCY = 0
    1422
    1523class MythLog:
    1624        """
    1725        A simple logging class
    1826        """
    19         def __init__(self, level, format, instance):
    20                 self.log = logging.getLogger(instance)
    21                 self.log.setLevel(level)
    22                 self.ch = logging.StreamHandler()
    23                 self.ch.setFormatter(logging.Formatter(format))
    24                 self.log.addHandler(self.ch)
    2527
    26         def Msg(self, level, msg, *args, **kwargs):
    27                 self.log.log(level, msg, *args, **kwargs)
     28        priority = WARNING
    2829
     30        def __init__(self, priority=WARNING, module='pythonbindings', mode=3):
     31                self.setPriority(priority)
     32                if isinstance(module,str):
     33                        self.mod = module
     34                self.host = gethostname()
     35                self.mode = mode
     36                if db.getSetting('LogEnabled') == 0:
     37                        self.mode %= 2
     38
     39        def setPriority(self, priority):
     40                if priority in range(0,9):
     41                        self.priority = priority
     42
     43        def log(self, priority, message, detail=''):
     44                if priority > self.priority:
     45                        return
     46                now = datetime.now()
     47                nowstr = None
     48                if (version_info[0] > 2) | (version_info[1] > 5):
     49                        nowstr = now.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
     50                else:
     51                        nowstr = now.strftime('%Y-%m-%d %H:%M:%S.000')
     52                if self.mode & 1:
     53                        if len(detail):
     54                                print "%s %s: %s -- %s" % (nowstr, self.mod, message, detail)
     55                        else:
     56                                print "%s %s: %s" % (nowstr, self.mod, message)
     57                if self.mode & 2:
     58                        cursor = db.cursor()
     59                        cursor.execute("""INSERT INTO mythlog
     60                                (module, priority, logdate, host, message, details)
     61                                VALUES (%s, %s, %s, %s, %s, %s)""",
     62                                (self.mod,priority,now,self.host,message,detail))
     63
     64        def all(self, message, detail=''):
     65                self.log(ALL,message,detail)
     66
     67        def debug(self, message, detail=''):
     68                self.log(DEBUG,message,detail)
     69
     70        def info(self, message, detail=''):
     71                self.log(INFO,message,detail)
     72
     73        def notice(self, message, detail=''):
     74                self.log(NOTICE,message,detail)
     75
     76        def warning(self, message, detail=''):
     77                self.log(WARNING,message,detail)
     78
     79        def error(self, message, detail=''):
     80                self.log(ERROR,message,detail)
     81
     82        def critical(self, message, detail=''):
     83                self.log(CRITICAL,message,detail)
     84
     85        def alert(self, message, detail=''):
     86                self.log(ALERT,message,detail)
     87
     88        def emergency(self, message, detail=''):
     89                self.log(EMERGENCY,message,detail)
     90
    2991class MythError:
    3092        """
    3193        A simple exception class
     
    3698        def __repr__(self):
    3799                print ': ' + self.message
    38100
     101
    39102# vim: ts=4 sw=4:
  • MythTV/MythDB.py

     
    1010import getopt
    1111from datetime import datetime
    1212
    13 from MythLog import *
    14 
    15 # create logging object
    16 log = MythLog(CRITICAL, '#%(levelname)s - %(message)s', 'MythDB')
    17 
    1813# check for dependency
    1914try:
    2015        import MySQLdb
    2116except:
    22         log.Msg(CRITICAL, "MySQLdb (python-mysqldb) is required but is not found.")
    23         sys.exit(1)
     17        raise MythError("MySQLdb (python-mysqldb) is required but is not found.")
    2418
    2519class MythDB:
    2620        """
     
    7367                                        pass
    7468
    7569                        if dbconn['host'] != None and dbconn['name'] != None and dbconn['user'] != None and dbconn['pass'] != None:
    76                                 log.Msg(INFO, 'Using config %s', config_file)
     70#                               log.Msg(INFO, 'Using config %s', config_file)
    7771                                found_config = True
    7872                                break
    7973
     
    9791
    9892                try:
    9993                        self.db = MySQLdb.connect(user=dbconn['user'], host=dbconn['host'], passwd=dbconn['pass'], db=dbconn['name'], use_unicode=True, charset='utf8')
    100                         log.Msg(INFO, 'DB Connection info (host:%s, name:%s, user:%s, pass:%s)', dbconn['host'], dbconn['name'], dbconn['user'], dbconn['pass'])
     94#                       log.Msg(INFO, 'DB Connection info (host:%s, name:%s, user:%s, pass:%s)', dbconn['host'], dbconn['name'], dbconn['user'], dbconn['pass'])
    10195                except:
    10296                        raise MythError('Connection failed for \'%s\'@\'%s\' to database %s using password %s' % (dbconn['user'], dbconn['host'], dbconn['name'], dbconn['pass']))
    10397
     
    108102                Returns None if there are no settings. If multiple rows are
    109103                found (multiple hostnames), returns the value of the first one.
    110104                """
    111                 log.Msg(DEBUG, 'Retrieving all setting for host %s', hostname)
     105#               log.Msg(DEBUG, 'Retrieving all setting for host %s', hostname)
    112106                c = self.db.cursor()
    113107                if hostname is None:
    114108                        c.execute("""
     
    136130                Returns None if the setting was not found. If multiple rows are
    137131                found (multiple hostnames), returns the value of the first one.
    138132                """
    139                 log.Msg(DEBUG, 'Looking for setting %s for host %s', value, hostname)
     133#               log.Msg(DEBUG, 'Looking for setting %s for host %s', value, hostname)
    140134                c = self.db.cursor()
    141135                if hostname is None:
    142136                        c.execute("""
     
    162156                """
    163157                Sets the value for the given MythTV setting.
    164158                """
    165                 log.Msg(DEBUG, 'Setting %s for host %s to %s', value, hostname, data)
     159#               log.Msg(DEBUG, 'Setting %s for host %s to %s', value, hostname, data)
    166160                c = self.db.cursor()
    167161                ws = None
    168162                ss = None