Edgewall Software

Ticket #7286: all-the-way_enhanced_logging.3.patch

File all-the-way_enhanced_logging.3.patch, 58.5 KB (added by palgarvio, 5 months ago)

Removed a testing log line

  • trac/attachment.py

     
    113113            self.resource = Resource(parent_realm_or_attachment_resource, 
    114114                                     parent_id).child('attachment', filename) 
    115115        self.env = env 
     116        self.log = self.env.get_logger(__name__) 
    116117        self.parent_realm = self.resource.parent.realm 
    117118        self.parent_id = unicode(self.resource.parent.id) 
    118119        if self.resource.id: 
     
    181182            try: 
    182183                os.unlink(self.path) 
    183184            except OSError: 
    184                 self.env.log.error('Failed to delete attachment file %s', 
    185                                    self.path, exc_info=True) 
     185                self.log.error('Failed to delete attachment file %s', 
     186                               self.path, exc_info=True) 
    186187                if handle_ta: 
    187188                    db.rollback() 
    188189                raise TracError(_('Could not delete attachment')) 
    189190 
    190         self.env.log.info('Attachment removed: %s' % self.title) 
     191        self.log.info('Attachment removed: %s', self.title) 
    191192        if handle_ta: 
    192193            db.commit() 
    193194 
     
    234235            shutil.copyfileobj(fileobj, targetfile) 
    235236            self.resource.id = self.filename = filename 
    236237 
    237             self.env.log.info('New attachment: %s by %s', self.title, 
    238                               self.author) 
     238            self.log.info('New attachment: %s by %s', self.title, self.author) 
    239239 
    240240            if handle_ta: 
    241241                db.commit() 
     
    270270        As this is usually done while deleting the parent resource, 
    271271        the `db` argument is ''not'' optional here. 
    272272        """ 
     273        log = env.get_logger(__name__) 
    273274        attachment_dir = None 
    274275        for attachment in list(cls.select(env, parent_realm, parent_id, db)): 
    275276            attachment_dir = os.path.dirname(attachment.path) 
     
    278279            try: 
    279280                os.rmdir(attachment_dir) 
    280281            except OSError: 
    281                 env.log.error("Can't delete attachment directory %s", 
    282                               attachment_dir, exc_info=True) 
     282                log.error("Can't delete attachment directory %s", 
     283                          attachment_dir, exc_info=True) 
    283284             
    284285    select = classmethod(select) 
    285286    delete_all = classmethod(delete_all) 
    286287 
    287288    def open(self): 
    288         self.env.log.debug('Trying to open attachment at %s', self.path) 
     289        self.log.debug('Trying to open attachment at %s', self.path) 
    289290        try: 
    290291            fd = open(self.path, 'rb') 
    291292        except IOError: 
     
    694695            add_link(req, 'alternate', raw_href, _('Original Format'), 
    695696                     mime_type) 
    696697 
    697             self.log.debug("Rendering preview of file %s with mime-type %s" 
    698                            % (attachment.filename, mime_type)) 
     698            self.log.debug("Rendering preview of file %s with mime-type %s", 
     699                           attachment.filename, mime_type) 
    699700 
    700701            data['preview'] = mimeview.preview_data( 
    701702                Context.from_request(req, attachment.resource), fd, 
     
    772773        if legacy_action: 
    773774            decision = legacy_action in perm 
    774775            if not decision: 
    775                 self.env.log.debug('LegacyAttachmentPolicy denied %s ' 
    776                                    'access to %s. User needs %s' % 
    777                                    (username, resource, legacy_action)) 
     776                self.log.debug('LegacyAttachmentPolicy denied %s ' 
     777                               'access to %s. User needs %s', 
     778                               username, resource, legacy_action) 
    778779            return decision 
    779780        else: 
    780781            for d in self.delegates: 
  • trac/env.py

     
    22# 
    33# Copyright (C) 2003-2008 Edgewall Software 
    44# Copyright (C) 2003-2007 Jonas Borgström <jonas@edgewall.com> 
     5# Copyright (C) 2008 Pedro Algarvio <ufs@ufsoft.org> 
    56# All rights reserved. 
    67# 
    78# This software is licensed as described in the file COPYING, which 
     
    1415# 
    1516# Author: Jonas Borgström <jonas@edgewall.com> 
    1617 
     18import logging 
    1719import os 
    1820try: 
    1921    import threading 
     
    147149         - $(path)s     the path for the current environment 
    148150         - $(basename)s the last path component of the current environment 
    149151         - $(project)s  the project name 
    150  
    151          Note the usage of `$(...)s` instead of `%(...)s` as the latter form 
    152          would be interpreted by the ConfigParser itself. 
    153  
    154          Example: 
     152         
     153        Note the usage of `$(...)s` instead of `%(...)s` as the latter form 
     154        would be interpreted by the ConfigParser itself. 
     155         
     156        Example: 
    155157         ($(thread)d) Trac[$(basename)s:$(module)s] $(levelname)s: $(message)s 
    156  
    157          (since 0.10.5)""") 
     158         
     159        (since 0.10.5)""") 
     160    log_filters = ListOption('logging', 'log_filters', [], doc= 
     161        """Custom logging handlers. 
     162         
     163        If nothing set, logging will be as it was, nothing is changed. 
     164         
     165        Example usage is: 
     166        log_filters = trac:WARNING, trac.ticket:DEBUG 
     167         
     168        The above would translate to: 
     169            * all messages who's module name starts with `trac` and log level 
     170            is higher than `WARNING` are logged; 
     171            * all messages who's module name starts with `trac.ticket` and log 
     172            level is higher than `DEBUG` are logged; 
     173            * all other messages who's module name does not start with any of 
     174            the above and for which their level is higher than the default 
     175            `log_level` will be logged; 
     176         
     177        This way you can narrow the debugging messages to the modules you 
     178        wish to. The same applies to a plugin you're coding: 
     179        log_filters = trac:ERROR, my.plug.module:DEBUG 
     180         
     181        (since 0.12)""") 
    158182 
    159183    def __init__(self, path, create=False, options=[]): 
    160184        """Initialize the Trac environment. 
     
    201225        environment configuration) and `log` (a logger object).""" 
    202226        component.env = self 
    203227        component.config = self.config 
    204         component.log = self.log 
     228        component.log = logging.getLogger( 
     229            "%s.%s" % (self.path, component.__class__.__module__) 
     230        ) 
    205231 
    206232    def is_component_enabled(self, cls): 
    207233        """Implemented to only allow activation of components that are not 
     
    353379 
    354380    def setup_log(self): 
    355381        """Initialize the logging sub-system.""" 
    356         from trac.log import logger_factory 
     382        from trac.log import setup_logging 
    357383        logtype = self.log_type 
    358384        logfile = self.log_file 
    359385        if logtype == 'file' and not os.path.isabs(logfile): 
     
    364390                     .replace('%(path)s', self.path) \ 
    365391                     .replace('%(basename)s', os.path.basename(self.path)) \ 
    366392                     .replace('%(project)s', self.project_name) 
    367         self.log = logger_factory(logtype, logfile, self.log_level, self.path, 
    368                                   format=format) 
     393        # Setup but don't keep the root logger  
     394        setup_logging(logtype, logfile, self.log_level, self.path, 
     395                      format, self.log_filters) 
     396         
     397        class CheckDeprecatedLoggingUsage(object): 
     398            """Proxy class to warn users of bad logging usage""" 
     399            log = logging.getLogger("%s.%s" % (self.path, __name__)) 
     400            def check_deprecated_use(self): 
     401                import inspect 
     402                caller = inspect.stack()[2] 
     403                if 'env.log' in caller[4][0]: 
     404                    self.log.warn( 
     405                        _("""Please stop logging through "env.log" on "%s". \ 
     406The code issuing this is "%s". This usage is now deprecated. Instead, if \ 
     407it's a trac Component, please use "self.log", if it's just a function which \ 
     408get's passed a trac env, get a logger like "log = env.get_logger(__name__)" \ 
     409and log through that. This practice provides good and usefull logging."""), 
     410                        caller[1], caller[4][0].strip()) 
     411                del caller 
     412            def __getattribute__(self, name): 
     413                if name in ('log', 'check_deprecated_use'): 
     414                    return object.__getattribute__(self, name) 
     415                self.check_deprecated_use() 
     416                return getattr(self.log, name) 
     417                 
     418        # Get a logger for this module 
     419        self.log = CheckDeprecatedLoggingUsage() 
     420         
     421    def get_logger(self, name): 
     422        """Get the correct logger for classes/functions which an env is passed, 
     423        yet, it's not subclassing Component.""" 
     424        from trac.log import get_logger 
     425        return get_logger(self.path, name) 
    369426 
    370427    def get_known_users(self, cnx=None): 
    371428        """Generator that yields information about all known users, i.e. users 
     
    557614                env.log.info('Reloading environment due to configuration ' 
    558615                             'change') 
    559616                env.shutdown() 
    560                 if hasattr(env.log, '_trac_handler'): 
    561                     hdlr = env.log._trac_handler 
    562                     env.log.removeHandler(hdlr) 
     617                env_root_logger = logging.getLogger(env.path) 
     618                if hasattr(env_root_logger, '_trac_handler'):                     
     619                    hdlr = env_root_logger._trac_handler 
     620                    env_root_logger.removeHandler(hdlr) 
    563621                    hdlr.close() 
     622                del env_root_logger 
    564623                del env_cache[env_path] 
    565624                env = None 
    566625            if env is None: 
  • trac/mimeview/enscript.py

     
    136136        mimetype = mimetype.split(';', 1)[0] # strip off charset 
    137137        mode = self._types[mimetype][0] 
    138138        cmdline += ' --color -h -q --language=html -p - -E%s' % mode 
    139         self.env.log.debug("Enscript command line: %s" % cmdline) 
     139        self.log.debug("Enscript command line: %s", cmdline) 
    140140 
    141141        np = NaivePopen(cmdline, content.encode('utf-8'), capturestderr=1) 
    142142        if np.errorlevel or np.err: 
  • trac/mimeview/php.py

     
    8181    def render(self, context, mimetype, content, filename=None, rev=None): 
    8282        # -n to ignore php.ini so we're using default colors 
    8383        cmdline = '%s -sn' % self.path 
    84         self.env.log.debug("PHP command line: %s" % cmdline) 
     84        self.log.debug("PHP command line: %s", cmdline) 
    8585 
    8686        content = content_to_unicode(self.env, content, mimetype) 
    8787        content = content.encode('utf-8') 
  • trac/ticket/tests/query.py

     
    1 from trac.log import logger_factory 
     1from trac.log import setup_logging 
    22from trac.mimeview import Context 
    33from trac.test import Mock, EnvironmentStub, MockPerm 
    44from trac.ticket.query import Query, QueryModule 
  • trac/ticket/report.py

     
    547547            # The column name is obtained. 
    548548            get_col_name_sql = 'SELECT * FROM ( ' + sql + ' ) AS tab LIMIT 1' 
    549549            cursor.execute(get_col_name_sql, args) 
    550             self.env.log.debug("Query SQL(Get col names): " + get_col_name_sql) 
     550            self.log.debug("Query SQL(Get col names): " + get_col_name_sql) 
    551551            cols = get_column_names(cursor) 
    552552 
    553553            sort_col = req.args.get('sort', '') 
  • trac/ticket/model.py

     
    4040 
    4141    def __init__(self, env, tkt_id=None, db=None, version=None): 
    4242        self.env = env 
     43        self.log = self.env.get_logger(__name__) 
    4344        self.resource = Resource('ticket', tkt_id, version) 
    4445        self.fields = TicketSystem(self.env).get_ticket_fields() 
    4546        self.values = {} 
     
    7778                    try: 
    7879                        default = options[int(default)] 
    7980                    except (ValueError, IndexError): 
    80                         self.env.log.warning('Invalid default value "%s" ' 
    81                                              'for custom field "%s"' 
    82                                              % (default, field['name'])) 
     81                        self.log.warning('Invalid default value "%s" for ' 
     82                                         'custom field "%s"', default, 
     83                                         field['name']) 
    8384            if default: 
    8485                self.values.setdefault(field['name'], default) 
    8586 
     
    350351        if not self.ticket_col: 
    351352            self.ticket_col = self.type 
    352353        self.env = env 
     354        self.log = self.env.get_logger(__name__) 
    353355        if name: 
    354356            name = simplify_whitespace(name) 
    355357        if name: 
     
    379381            handle_ta = False 
    380382 
    381383        cursor = db.cursor() 
    382         self.env.log.info('Deleting %s %s' % (self.type, self.name)) 
     384        self.log.info('Deleting %s %s', self.type, self.name) 
    383385        cursor.execute("DELETE FROM enum WHERE type=%s AND value=%s", 
    384386                       (self.type, self._old_value)) 
    385387        # Re-order any enums that have higher value than deleted (close gap) 
     
    407409            handle_ta = False 
    408410 
    409411        cursor = db.cursor() 
    410         self.env.log.debug("Creating new %s '%s'" % (self.type, self.name)) 
     412        self.log.debug("Creating new %s '%s'", self.type, self.name) 
    411413        if not self.value: 
    412414            cursor.execute(("SELECT COALESCE(MAX(%s),0) FROM enum " 
    413415                            "WHERE type=%%s") % db.cast('value', 'int'), 
     
    432434            handle_ta = False 
    433435 
    434436        cursor = db.cursor() 
    435         self.env.log.info('Updating %s "%s"' % (self.type, self.name)) 
     437        self.log.info('Updating %s "%s"', self.type, self.name) 
    436438        cursor.execute("UPDATE enum SET name=%s,value=%s " 
    437439                       "WHERE type=%s AND name=%s", 
    438440                       (self.name, self.value, self.type, self._old_name)) 
     
    494496 
    495497    def __init__(self, env, name=None, db=None): 
    496498        self.env = env 
     499        self.log = self.env.get_logger(__name__) 
    497500        if name: 
    498501            name = simplify_whitespace(name) 
    499502        if name: 
     
    525528            handle_ta = False 
    526529 
    527530        cursor = db.cursor() 
    528         self.env.log.info('Deleting component %s' % self.name) 
     531        self.log.info('Deleting component %s', self.name) 
    529532        cursor.execute("DELETE FROM component WHERE name=%s", (self.name,)) 
    530533 
    531534        self.name = self._old_name = None 
     
    544547            handle_ta = False 
    545548 
    546549        cursor = db.cursor() 
    547         self.env.log.debug("Creating new component '%s'" % self.name) 
     550        self.log.debug("Creating new component '%s'", self.name) 
    548551        cursor.execute("INSERT INTO component (name,owner,description) " 
    549552                       "VALUES (%s,%s,%s)", 
    550553                       (self.name, self.owner, self.description)) 
     
    563566            handle_ta = False 
    564567 
    565568        cursor = db.cursor() 
    566         self.env.log.info('Updating component "%s"' % self.name) 
     569        self.log.info('Updating component "%s"', self.name) 
    567570        cursor.execute("UPDATE component SET name=%s,owner=%s,description=%s " 
    568571                       "WHERE name=%s", 
    569572                       (self.name, self.owner, self.description, 
     
    596599 
    597600    def __init__(self, env, name=None, db=None): 
    598601        self.env = env 
     602        self.log = self.env.get_logger(__name__) 
    599603        if name: 
    600604            self._fetch(name, db) 
    601605            self._old_name = name 
     
    641645            handle_ta = False 
    642646 
    643647        cursor = db.cursor() 
    644         self.env.log.info('Deleting milestone %s' % self.name) 
     648        self.log.info('Deleting milestone %s', self.name) 
    645649        cursor.execute("DELETE FROM milestone WHERE name=%s", (self.name,)) 
    646650 
    647651        # Retarget/reset tickets associated with this milestone 
     
    667671 
    668672        self.name = simplify_whitespace(self.name) 
    669673        cursor = db.cursor() 
    670         self.env.log.debug("Creating new milestone '%s'" % self.name) 
     674        self.log.debug("Creating new milestone '%s'", self.name) 
    671675        cursor.execute("INSERT INTO milestone (name,due,completed,description) " 
    672676                       "VALUES (%s,%s,%s,%s)", 
    673677                       (self.name, to_timestamp(self.due), to_timestamp(self.completed), 
     
    686690 
    687691        self.name = simplify_whitespace(self.name) 
    688692        cursor = db.cursor() 
    689         self.env.log.info('Updating milestone "%s"' % self.name) 
     693        self.log.info('Updating milestone "%s"', self.name) 
    690694        cursor.execute("UPDATE milestone SET name=%s,due=%s," 
    691695                       "completed=%s,description=%s WHERE name=%s", 
    692696                       (self.name, to_timestamp(self.due), to_timestamp(self.completed), 
    693697                        self.description, 
    694698                        self._old_name)) 
    695         self.env.log.info('Updating milestone field of all tickets ' 
    696                           'associated with milestone "%s"' % self.name) 
     699        self.log.info('Updating milestone field of all tickets associated ' 
     700                      'with milestone "%s"', self.name) 
    697701        cursor.execute("UPDATE ticket SET milestone=%s WHERE milestone=%s", 
    698702                       (self.name, self._old_name)) 
    699703        self._old_name = self.name 
     
    726730 
    727731    def __init__(self, env, name=None, db=None): 
    728732        self.env = env 
     733        self.log = self.env.get_logger(__name__) 
    729734        if name: 
    730735            if not db: 
    731736                db = self.env.get_db_cnx() 
     
    755760            handle_ta = False 
    756761 
    757762        cursor = db.cursor() 
    758         self.env.log.info('Deleting version %s' % self.name) 
     763        self.log.info('Deleting version %s', self.name) 
    759764        cursor.execute("DELETE FROM version WHERE name=%s", (self.name,)) 
    760765 
    761766        self.name = self._old_name = None 
     
    774779            handle_ta = False 
    775780 
    776781        cursor = db.cursor() 
    777         self.env.log.debug("Creating new version '%s'" % self.name) 
     782        self.log.debug("Creating new version '%s'", self.name) 
    778783        cursor.execute("INSERT INTO version (name,time,description) " 
    779784                       "VALUES (%s,%s,%s)", 
    780785                       (self.name, to_timestamp(self.time), self.description)) 
     
    793798            handle_ta = False 
    794799 
    795800        cursor = db.cursor() 
    796         self.env.log.info('Updating version "%s"' % self.name) 
     801        self.log.info('Updating version "%s"', self.name) 
    797802        cursor.execute("UPDATE version SET name=%s,time=%s,description=%s " 
    798803                       "WHERE name=%s", 
    799804                       (self.name, to_timestamp(self.time), self.description, 
  • trac/ticket/roadmap.py

     
    648648                cursor.execute("UPDATE ticket SET milestone=%s WHERE " 
    649649                               "milestone=%s and status != 'closed'", 
    650650                                (retarget_to, old_name)) 
    651                 self.env.log.info('Tickets associated with milestone %s ' 
    652                                   'retargeted to %s' % (old_name, retarget_to)) 
     651                self.log.info('Tickets associated with milestone %s ' 
     652                              'retargeted to %s' % (old_name, retarget_to)) 
    653653        else: 
    654654            milestone.insert() 
    655655        db.commit() 
  • trac/ticket/query.py

     
    5353                 order=None, desc=0, group=None, groupdesc=0, verbose=0, 
    5454                 rows=None, page=None, max=None): 
    5555        self.env = env 
     56        self.log = self.env.get_logger(__name__) 
    5657        self.id = report # if not None, it's the corresponding saved query 
    5758        self.constraints = constraints or {} 
    5859        self.order = order 
     
    235236        cursor = db.cursor() 
    236237 
    237238        count_sql = 'SELECT COUNT(*) FROM (' + sql + ') AS foo' 
    238         # self.env.log.debug("Count results in Query SQL: " + count_sql %  
    239         #                    tuple([repr(a) for a in args])) 
     239        # self.log.debug("Count results in Query SQL: " + count_sql %  
     240        #                tuple([repr(a) for a in args])) 
    240241 
    241242        cnt = 0 
    242243        cursor.execute(count_sql, args); 
    243244        for cnt, in cursor: 
    244245            break 
    245         self.env.log.debug("Count results in Query: %d" % cnt) 
     246        self.log.debug("Count results in Query: %d", cnt) 
    246247        return cnt 
    247248 
    248249    def execute(self, req, db=None, cached_ids=None): 
     
    266267                raise TracError(_('Page %(page)s is beyond the number of ' 
    267268                                  'pages in the query', page=self.page)) 
    268269 
    269         self.env.log.debug("Query SQL: " + sql % tuple([repr(a) for a in args]))      
     270        self.log.debug("Query SQL: " + sql % tuple([repr(a) for a in args]))      
    270271        cursor.execute(sql, args) 
    271272        columns = get_column_names(cursor) 
    272273        fields = [] 
  • trac/htdocs/css/admin.css

     
    2121 
    2222#tabcontent { padding: 0.4em 2em; margin-left: 12em; min-height: 300px; } 
    2323#tabcontent h2 { color: #333; margin-top: 0; } 
    24 p.help { color: #666; font-size: 90%; margin: 1em .5em .5em; } 
     24div.help, p.help { color: #666; font-size: 90%; margin: 1em .5em .5em; } 
    2525 
    2626#enumlist tbody td { vertical-align: middle; } 
    2727 
  • trac/db/mysql_backend.py

     
    8787        from trac.db_default import schema 
    8888        for table in schema: 
    8989            for stmt in self.to_sql(table): 
    90                 self.env.log.debug(stmt) 
     90                self.log.debug(stmt) 
    9191                cursor.execute(stmt) 
    9292        cnx.commit() 
    9393 
  • trac/versioncontrol/tests/svn_fs.py

     
    3030except: 
    3131    has_svn = False 
    3232 
    33 from trac.log import logger_factory 
     33from trac.log import setup_logging 
    3434from trac.test import TestSetup 
    3535from trac.core import TracError 
    3636from trac.util.datefmt import utc 
     
    8585 
    8686    def setUp(self): 
    8787        self.repos = SubversionRepository(REPOS_PATH, None, 
    88                                           logger_factory('test')) 
     88                                          setup_logging('test')) 
    8989 
    9090    def tearDown(self): 
    9191        self.repos = None 
     
    460460 
    461461    def setUp(self): 
    462462        self.repos = SubversionRepository(REPOS_PATH + '/trunk', None, 
    463                                           logger_factory('test')) 
     463                                          setup_logging('test')) 
    464464 
    465465    def tearDown(self): 
    466466        self.repos = None 
     
    688688 
    689689    def setUp(self): 
    690690        self.repos = SubversionRepository(REPOS_PATH + '/trunk/dir1', None, 
    691                                           logger_factory('test')) 
     691                                          setup_logging('test')) 
    692692 
    693693    def tearDown(self): 
    694694        self.repos = None 
     
    708708 
    709709    def setUp(self): 
    710710        self.repos = SubversionRepository(REPOS_PATH + '/tags/v1', None, 
    711                                           logger_factory('test')) 
     711                                          setup_logging('test')) 
    712712 
    713713    def tearDown(self): 
    714714        self.repos = None 
     
    726726 
    727727    def setUp(self): 
    728728        self.repos = SubversionRepository(REPOS_PATH + '/branches', None, 
    729                                           logger_factory('test')) 
     729                                          setup_logging('test')) 
    730730 
    731731    def tearDown(self): 
    732732        self.repos = None 
  • trac/versioncontrol/tests/cache.py

     
    1616 
    1717from datetime import datetime 
    1818 
    19 from trac.log import logger_factory 
     19from trac.log import setup_logging 
    2020from trac.test import Mock, InMemoryDatabase 
    2121from trac.util.datefmt import to_timestamp, utc 
    2222from trac.versioncontrol import Repository, Changeset, Node, NoSuchChangeset 
     
    3030 
    3131    def setUp(self): 
    3232        self.db = InMemoryDatabase() 
    33         self.log = logger_factory('test') 
     33        self.log = setup_logging('test') 
    3434        cursor = self.db.cursor() 
    3535        cursor.execute("INSERT INTO system (name, value) VALUES (%s,%s)", 
    3636                       ('youngest_rev', '')) 
  • trac/admin/web_ui.py

     
    22# 
    33# Copyright (C) 2005-2008 Edgewall Software 
    44# Copyright (C) 2005 Jonas Borgström <jonas@edgewall.com> 
     5# Copyright (C) 2008 Pedro Algarvio <ufs@ufsoft.org> 
    56# All rights reserved.