use logging and not print statements (closes #64792)

authorAlexandre Fayolle <alexandre.fayolle@logilab.fr>
changeset2b49a49b23e2
branchdefault
phasepublic
hiddenno
parent revision#73a15ce9aadd backport stable
child revision#2b46b2376eb2 backport stable
files modified by this revision
__init__.py
mysql.py
postgres.py
sqlserver2005.py
# HG changeset patch
# User Alexandre Fayolle <alexandre.fayolle@logilab.fr>
# Date 1303464331 -7200
# Fri Apr 22 11:25:31 2011 +0200
# Node ID 2b49a49b23e2ac5a68ac817c5d1d865f72594afb
# Parent 73a15ce9aadda94fa47f1713b0bbff4e5c29ce51
use logging and not print statements (closes #64792)

diff --git a/__init__.py b/__init__.py
@@ -67,11 +67,11 @@
1      try:
2          mod = _ADAPTER_DIRECTORY.adapt(driver, prefered_drivers, pywrap=pywrap)
3      except NoAdapterFound, err:
4          if not quiet:
5              msg = 'No Adapter found for %s, returning native module'
6 -            print >> sys.stderr, msg % err.objname
7 +            _LOGGER.warning(msg,  err.objname)
8          mod = err.adapted_obj
9      return mod
10 
11  def get_connection(driver='postgres', host='', database='', user='',
12                    password='', port='', quiet=False, drivers=_PREFERED_DRIVERS,
@@ -81,12 +81,12 @@
13      module, modname = _import_driver_module(driver, drivers)
14      try:
15          adapter = _ADAPTER_DIRECTORY.get_adapter(driver, modname)
16      except NoAdapterFound, err:
17          if not quiet:
18 -            msg = 'No Adapter found for %s, using default one' % err.objname
19 -            print >> sys.stderr, msg
20 +            msg = 'No Adapter found for %s, using default one' 
21 +            _LOGGER.warning(msg, err.objname)
22          adapted_module = DBAPIAdapter(module, pywrap)
23      else:
24          adapted_module = adapter(module, pywrap)
25      if host and not port:
26          try:
@@ -176,16 +176,16 @@
27      if not driver in drivers:
28          raise UnknownDriver(driver)
29      for modname in drivers[driver]:
30          try:
31              if not quiet:
32 -                print >> sys.stderr, 'Trying %s' % modname
33 +                _LOGGER.info('Trying %s', modname)
34              module = load_module_from_name(modname, use_sys=False)
35              break
36          except ImportError:
37              if not quiet:
38 -                print >> sys.stderr, '%s is not available' % modname
39 +                _LOGGER.warning('%s is not available', modname)
40              continue
41      else:
42          raise ImportError('Unable to import a %s module' % driver)
43      return module, modname
44 
@@ -278,19 +278,20 @@
45          :type native_module: module
46          :param native_module: the database's driver adapted module
47          """
48          self._native_module = native_module
49          self._pywrap = pywrap
50 +        self.logger = _LOGGER
51          # optimization: copy type codes from the native module to this instance
52          # since the .process_value method may be heavily used
53          for typecode in ('STRING', 'BOOLEAN', 'BINARY', 'DATETIME', 'NUMBER',
54                           'UNKNOWN'):
55              try:
56                  setattr(self, typecode, getattr(self, typecode))
57              except AttributeError:
58 -                print >>sys.stderr, 'WARNING: %s adapter has no %s type code' \
59 -                      % (self, typecode)
60 +                self.logger.warning('%s adapter has no %s type code',
61 +                                    self, typecode)
62 
63      def connect(self, host='', database='', user='', password='', port='',
64                  extra_args=None):
65          """Wraps the native module connect method"""
66          kwargs = {'host' : host, 'port' : port, 'database' : database,
@@ -572,10 +573,11 @@
67 
68      def __init__(self, encoding='utf-8', _cnx=None):
69          self.dbencoding = encoding
70          self._cnx = _cnx
71          self.dbapi_module = get_dbapi_compliant_module(self.backend_name)
72 +        self.logger = _LOGGER
73 
74      def __repr__(self):
75          if self.dbname is not None:
76              return '<lgdbhelper %s@%s [%s] @%#x>' % (self.dbname, self.dbhost,
77                                                       self.backend_name, id(self))
@@ -598,14 +600,14 @@
78 
79          you should first call record_connection_info to set connection
80          paramaters.
81          """
82          if self.dbuser:
83 -            _LOGGER.info('connecting to %s@%s for user %s', self.dbname,
84 +            self.logger.info('connecting to %s@%s for user %s', self.dbname,
85                           self.dbhost or 'localhost', self.dbuser)
86          else:
87 -            _LOGGER.info('connecting to %s@%s', self.dbname,
88 +            self.logger.info('connecting to %s@%s', self.dbname,
89                           self.dbhost or 'localhost')
90          cnx = self.dbapi_module.connect(self.dbhost, self.dbname,
91                                          self.dbuser,self.dbpasswd,
92                                          port=self.dbport,
93                                          extra_args=self.dbextraargs)
diff --git a/mysql.py b/mysql.py
@@ -99,11 +99,11 @@
94              return value.tostring()
95          return value
96 
97      def type_code_test(self, cursor):
98          for typename in ('STRING', 'BOOLEAN', 'BINARY', 'DATETIME', 'NUMBER'):
99 -            print typename, getattr(self, typename)
100 +            self.logger.debug('%s %s', typename, getattr(self, typename))
101          try:
102              cursor.execute("""CREATE TABLE _type_code_test(
103              varchar_field varchar(50),
104              text_field text unicode,
105              mtext_field mediumtext,
@@ -112,14 +112,14 @@
106              lblob_field longblob
107              )""")
108              cursor.execute("INSERT INTO _type_code_test VALUES ('1','2','3','4', '5', '6')")
109              cursor.execute("SELECT * FROM _type_code_test")
110              descr = cursor.description
111 -            print 'db fields type codes'
112 +            self.logger.info('db fields type codes')
113              for i, name in enumerate(('varchar', 'text', 'mediumtext',
114                                        'binary', 'blob', 'longblob')):
115 -                print name, descr[i]
116 +                self.logger.info('%s %s', name, descr[i])
117          finally:
118              cursor.execute("DROP TABLE _type_code_test")
119 
120 
121  db._PREFERED_DRIVERS['mysql'] = ['MySQLdb']#, 'pyMySQL.MySQL']
diff --git a/postgres.py b/postgres.py
@@ -114,11 +114,11 @@
122              extensions.register_type(psycopg2._psycopg.MXTIME)
123              # StringIO/cStringIO adaptation
124              # XXX (syt) todo, see my december discussion on the psycopg2 list
125              # for a working solution
126              #def adapt_stringio(stringio):
127 -            #    print 'ADAPTING', stringio
128 +            #    self.logger.info('ADAPTING %s', stringio)
129              #    return psycopg2.Binary(stringio.getvalue())
130              #import StringIO
131              #extensions.register_adapter(StringIO.StringIO, adapt_stringio)
132              #import cStringIO
133              #extensions.register_adapter(cStringIO.StringIO, adapt_stringio)
@@ -249,14 +249,14 @@
134      def create_language(self, cursor, extlang):
135          """postgres specific method to install a procedural language on a database"""
136          # make sure plpythonu is not directly in template1
137          cursor.execute("SELECT * FROM pg_language WHERE lanname='%s';" % extlang)
138          if cursor.fetchall():
139 -            print '%s language already installed' % extlang
140 +            self.logger.warning('%s language already installed', extlang)
141          else:
142              cursor.execute('CREATE LANGUAGE %s' % extlang)
143 -            print '%s language installed' % extlang
144 +            self.logger.info('%s language installed', extlang)
145 
146      def list_users(self, cursor):
147          """return the list of existing database users"""
148          cursor.execute("SELECT usename FROM pg_user")
149          return [r[0] for r in cursor.fetchall()]
@@ -386,19 +386,19 @@
150          tstables = []
151          for table in self.list_tables(cursor):
152              if table.startswith('pg_ts'):
153                  tstables.append(table)
154          if tstables:
155 -            print 'pg_ts_dict already present, do not execute tsearch2.sql'
156 +            self.logger.info('pg_ts_dict already present, do not execute tsearch2.sql')
157              if owner:
158 -                print 'reset pg_ts* owners'
159 +                self.logger.info('reset pg_ts* owners')
160                  for table in tstables:
161                      cursor.execute('ALTER TABLE %s OWNER TO %s' % (table, owner))
162          else:
163              fullpath = self.find_tsearch2_schema()
164              cursor.execute(open(fullpath).read())
165 -            print 'tsearch2.sql installed'
166 +            self.logger.info('tsearch2.sql installed')
167 
168      def sql_init_fti(self):
169          """Return the sql definition of table()s used by the full text index.
170 
171          Require extensions to be already in.
diff --git a/sqlserver2005.py b/sqlserver2005.py
@@ -309,12 +309,12 @@
172          while err_count < 10 and same_size_count < 10:
173              time.sleep(1)
174              try:
175                  size = os.path.getsize(file_share_filename)
176              except OSError, exc:
177 +                self.logger.exception('error accessing %s', file_share_filename)
178                  err_count += 1
179 -                print exc
180              if size > prev_size:
181                  same_size_count = 0
182                  prev_size = size
183              else:
184                  same_size_count += 1