Merge lp:~red15/magentoerpconnect/fix-magentoerp-logging into lp:magentoerpconnect/oerp6.1-oldstable

Proposed by Niels Huylebroeck
Status: Merged
Merge reported by: Guewen Baconnier @ Camptocamp
Merged at revision: not available
Proposed branch: lp:~red15/magentoerpconnect/fix-magentoerp-logging
Merge into: lp:magentoerpconnect/oerp6.1-oldstable
Diff against target: 965 lines (+135/-137)
6 files modified
magentoerpconnect/magerp_core.py (+4/-5)
magentoerpconnect/magerp_osv.py (+30/-30)
magentoerpconnect/product.py (+53/-55)
magentoerpconnect/product_images.py (+14/-14)
magentoerpconnect/sale.py (+25/-24)
magentoerpconnect/stock.py (+9/-9)
To merge this branch: bzr merge lp:~red15/magentoerpconnect/fix-magentoerp-logging
Reviewer Review Type Date Requested Status
Guewen Baconnier @ Camptocamp Approve
Review via email: mp+107348@code.launchpad.net

Description of the change

Replaced all logging calls for modules contained in the magentoerp branch, there are more modules that need fixing but they would have to be pulled into this branch first I suppose?

To post a comment you must log in.
Revision history for this message
Guewen Baconnier @ Camptocamp (gbaconnier-c2c) wrote :

Thanks for your contribution !
It's merged

review: Approve
634. By Niels Huylebroeck

[MRG] Replaced all netsvc.Logger() calls with the appropriate logging.getLogger() and also adjusted the logging calls themselves.

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'magentoerpconnect/magerp_core.py'
2--- magentoerpconnect/magerp_core.py 2012-05-15 11:49:38 +0000
3+++ magentoerpconnect/magerp_core.py 2012-05-25 09:04:23 +0000
4@@ -25,7 +25,7 @@
5 from osv import osv, fields
6 import magerp_osv
7 import pooler
8-import netsvc
9+import logging
10 import base64, urllib
11 from magerp_osv import Connection
12 import tools
13@@ -67,7 +67,7 @@
14 'magento_referential': fields.function(_is_magento_referential, type="boolean", method=True, string="Magento Referential"),
15 'last_imported_product_id': fields.integer('Last Imported Product Id', help="Product are imported one by one. This is the magento id of the last product imported. If you clear it all product will be imported"),
16 'last_imported_partner_id': fields.integer('Last Imported Partner Id', help="Partners are imported one by one. This is the magento id of the last partner imported. If you clear it all partners will be imported"),
17- 'import_all_attributs': fields.boolean('Import all attributs', help="If the option is uncheck only the attributs that doesn't exist in OpenERP will be imported"),
18+ 'import_all_attributs': fields.boolean('Import all attributs', help="If the option is uncheck only the attributs that doesn't exist in OpenERP will be imported"),
19 'import_image_with_product': fields.boolean('With image', help="If the option is check the product's image and the product will be imported at the same time and so the step '7-import images' is not needed"),
20 'import_links_with_product': fields.boolean('With links', help="If the option is check the product's links (Up-Sell, Cross-Sell, Related) and the product will be imported at the same time and so the step '8-import links' is not needed"),
21 }
22@@ -123,7 +123,7 @@
23 def sync_attribs(self, cr, uid, ids, context=None):
24 attr_obj = self.pool.get('magerp.product_attributes')
25 attr_set_obj = self.pool.get('magerp.product_attribute_set')
26- logger = netsvc.Logger()
27+ logger = logging.getLogger('ext synchro')
28 for referential in self.browse(cr, uid, ids, context=context):
29 attr_conn = referential.external_connection(DEBUG, context=context)
30 attrib_set_ids = attr_set_obj.search(cr, uid, [('referential_id', '=', referential.id)])
31@@ -146,7 +146,7 @@
32 attributes_imported.append(ext_id)
33 attr_obj.ext_import(import_cr, uid, [attribut], referential.id, defaults={'referential_id':referential.id}, context={'referential_id':referential.id})
34 import_cr.commit()
35- logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "All attributs for the attributs set id %s was succesfully imported" %(attr_set_id))
36+ logger.info("All attributs for the attributs set id %s was succesfully imported", attr_set_id)
37 #Relate attribute sets & attributes
38 mage_inp = {}
39 #Pass in {attribute_set_id:{attributes},attribute_set_id2:{attributes}}
40@@ -263,7 +263,6 @@
41 return conn.call('catalog_product_link.types')
42
43 def sync_images(self, cr, uid, ids, context=None):
44- logger = netsvc.Logger()
45 product_obj = self.pool.get('product.product')
46 image_obj = self.pool.get('product.images')
47 import_cr = pooler.get_db(cr.dbname).cursor()
48
49=== modified file 'magentoerpconnect/magerp_osv.py'
50--- magentoerpconnect/magerp_osv.py 2012-05-24 06:57:34 +0000
51+++ magentoerpconnect/magerp_osv.py 2012-05-25 09:04:23 +0000
52@@ -24,7 +24,7 @@
53 import time
54 import datetime
55 import xmlrpclib
56-import netsvc
57+import logging
58 import urllib2
59 import base64
60 import pooler
61@@ -39,7 +39,7 @@
62 def __init__(self, location, username, password, debug=False):
63 #Append / if not there
64 if not location[-1] == '/':
65- location += '/'
66+ location += '/'
67 self.corelocation = location
68 #Please do not remove the str indeed xmlrpc lib require a string for the location
69 #if an unicode is send it will raise you an error
70@@ -48,33 +48,33 @@
71 self.password = password
72 self.debug = False
73 self.result = {}
74- self.logger = netsvc.Logger()
75-
76-
77+ self.logger = logging.getLogger('Connection(%s)' % self.location)
78+
79+
80 def connect(self):
81 if not self.location[-1] == '/':
82 self.location += '/'
83 if self.debug:
84- self.logger.notifyChannel(_("Magento Connection"), netsvc.LOG_INFO, _("Attempting connection with Settings:%s,%s,%s") % (self.location, self.username, self.password))
85+ self.logger.info(_("Attempting connection with Settings:%s,%s,%s"), self.location, self.username, self.password)
86 self.ser = xmlrpclib.ServerProxy(self.location)
87 for sleep_time in [1, 3, 6]:
88 try:
89 self.session = self.ser.login(self.username, self.password)
90 if self.debug:
91- self.logger.notifyChannel(_("Magento Connection"), netsvc.LOG_INFO, _("Login Successful"))
92+ self.logger.info(_("Login Successful"))
93 return True
94 except IOError, e:
95- self.logger.notifyChannel(_("Magento Connection"), netsvc.LOG_ERROR, _("Error in connecting:%s") % (e))
96- self.logger.notifyChannel(_("Magento Call"), netsvc.LOG_WARNING, _("Webservice Failure, sleeping %s second before next attempt") % (sleep_time))
97+ self.logger.error(_("Error in connecting:%s"), e, exc_info=True)
98+ self.logger.warn(_("Webservice Failure, sleeping %s second before next attempt"), sleep_time)
99 time.sleep(sleep_time)
100 except Exception,e:
101- self.logger.notifyChannel(_("Magento Connection"), netsvc.LOG_ERROR, _("Error in connecting:%s") % (e))
102- self.logger.notifyChannel(_("Magento Call"), netsvc.LOG_WARNING, _("Webservice Failure, sleeping %s second before next attempt") % (sleep_time))
103- time.sleep(sleep_time)
104- raise osv.except_osv(_('User Error'), _('Error when try to connect to magento, are your sure that your login is right? Did openerp can access to your magento?'))
105-
106-
107- def call(self, method, *arguments):
108+ self.logger.error(_("Error in connecting:%s"), e, exc_info=True)
109+ self.logger.warn(_("Webservice Failure, sleeping %s second before next attempt"), sleep_time)
110+ time.sleep(sleep_time)
111+ raise osv.except_osv(_('User Error'), _('Error connecting to magento, are your sure that your login is right? Did you configure API user in magento?'))
112+
113+
114+ def call(self, method, *arguments):
115 if arguments:
116 arguments = list(arguments)[0]
117 else:
118@@ -82,18 +82,18 @@
119 for sleep_time in [1, 3, 6]:
120 try:
121 if self.debug:
122- self.logger.notifyChannel(_("Magento Connection"), netsvc.LOG_INFO, _("Calling Method:%s,Arguments:%s") % (method, arguments))
123+ self.logger.info(_("Calling Method:%s,Arguments:%s"), method, arguments)
124 res = self.ser.call(self.session, method, arguments)
125 if self.debug:
126 if method=='catalog_product.list':
127 # the response of the method catalog_product.list can be very very long so it's better to see it only if debug log is activate
128- self.logger.notifyChannel(_("Magento Connection"), netsvc.LOG_DEBUG, _("Query Returned:%s") % (res))
129+ self.logger.debug(_("Query Returned:%s"), res)
130 else:
131- self.logger.notifyChannel(_("Magento Connection"), netsvc.LOG_INFO, _("Query Returned:%s") % (res))
132+ self.logger.info(_("Query Returned:%s"), res)
133 return res
134 except IOError, e:
135- self.logger.notifyChannel(_("Magento Call"), netsvc.LOG_ERROR, _("Method: %s\nArguments:%s\nError:%s") % (method, arguments, e))
136- self.logger.notifyChannel(_("Magento Call"), netsvc.LOG_WARNING, _("Webservice Failure, sleeping %s second before next attempt") % (sleep_time))
137+ self.logger.error(_("Method: %s\nArguments:%s\nError:%s"), method, arguments, e, exc_info=True)
138+ self.logger.warn(_("Webservice Failure, sleeping %s second before next attempt"), sleep_time)
139 time.sleep(sleep_time)
140 raise
141
142@@ -118,7 +118,7 @@
143 _DELETE_METHOD = False
144 _mapping = {}
145 DEBUG = False
146-
147+
148 #TODO deprecated, remove use
149 def mage_to_oe(self, cr, uid, mageid, instance, *arguments):
150 """given a record id in the Magento referential, returns a tuple (id, name) with the id in the OpenERP referential; Magento instance wise"""
151@@ -143,7 +143,7 @@
152 read = self.read(cr, uid, oeid, [self._rec_name])
153 return (read[0]['id'], read[0][self._rec_name])
154 return False
155-
156+
157 #TODO deprecated, remove use
158 def sync_import(self, cr, uid, magento_records, instance, debug=False, defaults=None, *attrs):
159
160@@ -178,7 +178,7 @@
161 'temp_vars':{},
162 'mage2oe_filters':mage2oe_filters
163 }
164-
165+
166 #now properly mapp known Magento attributes to OpenERP entity columns:
167 for each_valid_key in self._mapping:
168 if each_valid_key in magento_record.keys():
169@@ -216,7 +216,7 @@
170 self.record_save(cr, uid, rec_id, vals, defaults)
171 else:
172 self.record_save(cr, uid, rec_id, vals, defaults)
173-
174+
175 def record_save(self, cr, uid, rec_id, vals, defaults):
176 if defaults:
177 for key in defaults.keys():
178@@ -227,7 +227,7 @@
179 else:
180 #Record is not there, create it
181 self.create(cr, uid, vals,)
182-
183+
184 def cast_string(self, subject):
185 """This function will convert string objects to the data type required. Example "0"/"1" to boolean conversion"""
186 for key in subject.keys():
187@@ -237,7 +237,7 @@
188 else:
189 subject[key] = True
190 return subject
191-
192+
193 def mage_import_base(self,cr,uid,conn, external_referential_id, defaults=None, context=None):
194 if context is None:
195 context = {}
196@@ -259,7 +259,7 @@
197 list_method = self.pool.get('external.mapping').read(cr,uid,mapping_id[0],['external_list_method']).get('external_list_method',False)
198 if list_method:
199 data = conn.call(list_method, context['ids_or_filter'])
200-
201+
202 #it may happen that list method doesn't provide enough information, forcing us to use get_method on each record (case for sale orders)
203 if context.get('one_by_one', False):
204 self.mage_import_one_by_one(cr, uid, conn, external_referential_id, mapping_id[0], data, defaults, context)
205@@ -337,7 +337,7 @@
206 self.sync_import(cr, uid, magento_records, instance, debug, defaults)
207 else:
208 raise osv.except_osv(_('Undefined List method !'), _("list method is undefined for this object!"))
209-
210+
211 #TODO deprecated, remove use
212 def get_all_mage_ids(self, cr, uid, ids, instance=False):
213 search_param = []
214@@ -350,4 +350,4 @@
215 for each in reads:
216 mageids.append(each[self._MAGE_FIELD])
217 return mageids
218-
219+
220
221=== modified file 'magentoerpconnect/product.py'
222--- magentoerpconnect/product.py 2012-05-16 14:02:43 +0000
223+++ magentoerpconnect/product.py 2012-05-25 09:04:23 +0000
224@@ -28,7 +28,7 @@
225 import pooler
226 import magerp_osv
227 from tools.translate import _
228-import netsvc
229+import logging
230 import unicodedata
231 import base64, urllib
232 import os
233@@ -293,7 +293,7 @@
234
235 def init(self, cr):
236 """ Replace product_product by product.product
237- and product_template by product.template for
238+ and product_template by product.template for
239 consistency with model names"""
240 cr.execute("UPDATE magerp_product_attributes SET based_on = REPLACE(based_on, '_', '.')")
241 cr.execute("UPDATE magerp_product_attributes SET based_on = 'product.template' WHERE based_on IS NULL")
242@@ -561,12 +561,11 @@
243 " result = [('%(attribute_code)s', [option.value for option in options])]") % \
244 ({'field_name': field_name, 'attribute_code': attribute.attribute_code})
245 elif ttype in ['binary']:
246- logger = netsvc.Logger()
247- warning_text = "Binary mapping is actually not supported (attribute: %s)" % (attribute.attribute_code,)
248- logger.notifyChannel('ext synchro mapping', netsvc.LOG_WARNING, warning_text)
249- warning_msg = ("import netsvc\n"
250- "logger = netsvc.Logger()\n"
251- "logger.notifyChannel('ext synchro mapping', netsvc.LOG_WARNING, '%s')") % (warning_text,)
252+ logger = logging.getLogger('ext synchro mapping')
253+ logger.warn("Binary mapping is actually not supported (attribute: %s)", attribute.attribute_code)
254+ warning_msg = ("import logging\n"
255+ "logger = logging.getLogger('ext synchro mapping')\n"
256+ "logger.warn('Binary mapping is actually not supported (attribute: %%s)', %s)") % (attribute.attribute_code)
257 in_function = out_function = warning_msg
258 return in_function, out_function
259
260@@ -682,7 +681,7 @@
261 _name = "magerp.product_attribute_set"
262 _description = "Attribute sets in products"
263 _rec_name = 'attribute_set_name'
264-
265+
266 _columns = {
267 'sort_order':fields.integer('Sort Order'),
268 'attribute_set_name':fields.char('Set Name', size=100),
269@@ -731,7 +730,7 @@
270 cr.execute(query)
271
272 return True
273-
274+
275 magerp_product_attribute_set()
276
277 class magerp_product_attribute_groups(magerp_osv.magerp_osv):
278@@ -744,7 +743,7 @@
279 for attribute_group in self.browse(cr, uid, ids, context):
280 res[attribute_group.id] = self.pool.get('magerp.product_attribute_set').extid_to_oeid(cr, uid, attribute_group.attribute_set_id, attribute_group.referential_id.id)
281 return res
282-
283+
284 _columns = {
285 'attribute_set_id':fields.integer('Attribute Set ID'),
286 'attribute_set':fields.function(_get_set, type="many2one", relation="magerp.product_attribute_set", method=True, string="Attribute Set"),
287@@ -758,7 +757,7 @@
288 class product_tierprice(osv.osv):
289 _name = "product.tierprice"
290 _description = "Implements magento tier pricing"
291-
292+
293 _columns = {
294 'web_scope':fields.selection([
295 ('all', 'All Websites'),
296@@ -799,7 +798,7 @@
297
298 class product_mag_osv(magerp_osv.magerp_osv):
299 _register = False # Set to false if the model shouldn't be automatically discovered.
300-
301+
302 #remember one thing in life: Magento lies: it tells attributes are required while they are awkward to fill
303 #and will have a nice default vaule anyway, that's why we avoid making them mandatory in the product view
304 _magento_fake_mandatory_attrs = ['created_at', 'updated_at', 'has_options', 'required_options', 'model']
305@@ -880,7 +879,7 @@
306 cr, uid, oerp_group_id,
307 ['attribute_group_name'],
308 context=context)['attribute_group_name']
309-
310+
311 # Create a page for each attribute group
312 attr_group_fields_rel.setdefault(group_name, [])
313 while True:
314@@ -954,7 +953,7 @@
315 wf, fields_get['websites_ids'], context=context)
316
317 return notebook
318-
319+
320 def _filter_fields_to_return(self, cr, uid, field_names, context=None):
321 '''This function is a hook in order to filter the fields that appears on the view'''
322 return field_names
323@@ -1067,13 +1066,13 @@
324 #TODO base the import on the mapping and the function ext_import
325 def import_product_image(self, cr, uid, id, referential_id, conn, ext_id=None, context=None):
326 image_obj = self.pool.get('product.images')
327- logger = netsvc.Logger()
328+ logger = logging.getLogger('ext synchro')
329 if not ext_id:
330 ext_id = self.oeid_to_extid(cr, uid, id, referential_id, context=None)
331- # TODO everythere will should pass the params 'id' for magento api in order to force
332+ # TODO everythere will should pass the params 'id' for magento api in order to force
333 # to use the id as external key instead of mixed id/sku
334 img_list = conn.call('catalog_product_attribute_media.list', [ext_id, False, 'id'])
335- logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "Magento image for product ext_id %s: %s" %(ext_id, img_list))
336+ logger.info("Magento image for product ext_id %s: %s", ext_id, img_list)
337 images_name = []
338 for image in img_list:
339 img=False
340@@ -1083,13 +1082,13 @@
341 data = f.read()
342 f.close()
343 if "DOCTYPE html PUBLIC" in data:
344- logger.notifyChannel('ext synchro', netsvc.LOG_WARNING, "failed to open the image %s from Magento" % (image['url'],))
345+ logger.warn("Failed to open the image %s from Magento", image['url'])
346 continue
347 else:
348 img = base64.encodestring(data)
349 except Exception, e:
350 #TODO raise correctly the error
351- logger.notifyChannel('ext synchro', netsvc.LOG_WARNING, "failed to open the image %s from Magento, error : %s" % (image['url'],e))
352+ logger.error("Failed to open the image %s from Magento, error : %s", image['url'], e, exc_info=True)
353 continue
354 mag_filename, extention = os.path.splitext(os.path.basename(image['file']))
355 data = {'name': image['label'] and not image['label'] in images_name and image['label'] or mag_filename,
356@@ -1115,7 +1114,7 @@
357 new_image_id = image_obj.create(cr, uid, data, context=context)
358 image_obj.create_external_id_vals(cr, uid, new_image_id, image['file'], referential_id, context=context)
359 return True
360-
361+
362 def extid_to_existing_oeid(self, cr, uid, id, external_referential_id, context=None):
363 """Returns the OpenERP id of a resource by its external id.
364 Returns False if the resource does not exist."""
365@@ -1180,7 +1179,7 @@
366 else:
367 return False
368 tier_price = False
369- if 'x_magerp_tier_price' in vals.keys():
370+ if 'x_magerp_tier_price' in vals.keys():
371 tier_price = vals.pop('x_magerp_tier_price')
372 tp_obj = self.pool.get('product.tierprice')
373 #Delete existing tier prices
374@@ -1193,7 +1192,7 @@
375 stat = super(product_product, self).write(cr, uid, ids, vals, context)
376 #Perform other operation
377 return stat
378-
379+
380 def create_tier_price(self, cr, uid, tier_price, instance, product_id):
381 tp_obj = self.pool.get('product.tierprice')
382 for each in eval(tier_price):
383@@ -1215,13 +1214,13 @@
384 tier_vals['web_scope'] = 'specific'
385 tier_vals['website_id'] = self.pool.get('external.shop.group').mage_to_oe(cr, uid, int(each['website_id']), instance)
386 tp_obj.create(cr, uid, tier_vals)
387-
388+
389 def create(self, cr, uid, vals, context=None):
390 tier_price = False
391 if vals.get('referential_id', False):
392 instance = vals['referential_id']
393 #Filter keys to be changed
394- if 'x_magerp_tier_price' in vals.keys():
395+ if 'x_magerp_tier_price' in vals.keys():
396 tier_price = vals.pop('x_magerp_tier_price')
397
398 crid = super(product_product, self).create(cr, uid, vals, context)
399@@ -1262,7 +1261,7 @@
400 raise osv.except_osv(_('Warning!'), _('This product is related to Magento. It can not be deleted!\nYou can change it Magento status to "Disabled" and uncheck the active box to hide it from OpenERP.'))
401 else:
402 return super(product_product, self).unlink(cr, uid, ids, context)
403-
404+
405 #TODO move part of this to declarative mapping CSV template
406 def extdata_from_oevals(self, cr, uid, external_referential_id, data_record, mapping_lines, defaults, context=None):
407 product_data = super(product_product, self).extdata_from_oevals(cr, uid, external_referential_id, data_record, mapping_lines, defaults, context) #Aapply custom/attributes mappings
408@@ -1275,10 +1274,10 @@
409 if isinstance(pl_default_id, int):
410 pl_default_id = [pl_default_id]
411 product_data.update({'price': self.pool.get('product.pricelist').price_get(cr, uid, pl_default_id, product.id, 1.0)[pl_default_id[0]]})
412-
413+
414 if not product_data.get('tax_class_id', False):
415 product_data.update({'tax_class_id': 2}) #FIXME hugly!
416-
417+
418 if not product_data.get('status', False):
419 product_data.update({'status': product.active and 1 or 0})
420
421@@ -1292,7 +1291,7 @@
422 product_data.update({'meta_keyword': product.name})
423 if not product_data.get('meta_description', False):
424 product_data.update({'meta_description': product.description_sale and product.description_sale[:255]})
425-
426+
427 return product_data
428
429 def oevals_from_extdata(self, cr, uid, external_referential_id, data_record, mapping_lines, key_for_external_id=None, parent_data=None, previous_lines=None, defaults=None, context=None):
430@@ -1350,7 +1349,7 @@
431 return ext_id
432
433 def action_before_exporting_grouped_product(self, cr, uid, id, external_referential_ids=None, defaults=None, context=None):
434- logger = netsvc.Logger()
435+ logger = logging.getLogger('ext synchro')
436 if context.get('mrp_is_installed', False):
437 bom_ids = self.read(cr, uid, id, ['bom_ids'])['bom_ids']
438 if len(bom_ids): # it has or is part of a BoM
439@@ -1361,18 +1360,18 @@
440 for row in results:
441 child_ids.append(row['product_id'])
442 quantities.update({row['product_id']: row['product_qty']})
443- if child_ids: #it is an assembly and it contains the products child_ids:
444+ if child_ids: #it is an assembly and it contains the products child_ids:
445 self.ext_export(cr, uid, child_ids, external_referential_ids, defaults, context) #so we export them
446 else:
447 return False
448 else:
449- logger.notifyChannel('ext synchro', netsvc.LOG_ERROR, "OpenERP 'grouped' products will export to Magento as 'grouped products' only if they have a BOM and if the 'mrp' BOM module is installed")
450+ logger.error("OpenERP 'grouped' products will export to Magento as 'grouped products' only if they have a BOM and if the 'mrp' BOM module is installed")
451 return quantities, child_ids
452
453 def action_before_exporting(self, cr, uid, id, product_type, external_referential_ids=None, defaults=None, context=None):
454 '''Hook to allow your external module to execute some code before exporting a product'''
455 return True
456-
457+
458 #todo move this code to a generic module
459 def get_last_update_date(self, cr, uid, product_read, context=None):
460 """if a product have a depends on other object like bom for grouped product, or other product for configurable
461@@ -1389,10 +1388,10 @@
462 if last_updated_bom_date > last_updated_date:
463 last_updated_date=last_updated_bom_date
464 else:
465- conn.logger.notifyChannel('ext synchro', netsvc.LOG_ERROR, "OpenERP 'grouped' products will export to Magento as 'grouped products' only if they have a BOM and if the 'mrp' BOM module is installed")
466+ conn.logger.error("OpenERP 'grouped' products will export to Magento as 'grouped products' only if they have a BOM and if the 'mrp' BOM module is installed")
467 return last_updated_date
468-
469-
470+
471+
472 def get_ordered_ids(self, cr, uid, ids, external_referential_ids=None, defaults=None, context=None):
473 #TODO pass the shop better than the referentials
474 dates_2_ids = []
475@@ -1408,7 +1407,7 @@
476 read = cr.dictfetchall()
477 ids = []
478 context['force']=True
479-
480+
481 for product_read in read:
482 last_updated_date = self.get_last_update_date(cr, uid, product_read, context=context)
483 if last_exported_date and last_updated_date < last_exported_date:
484@@ -1474,7 +1473,7 @@
485 context['default_set_id'] = default_set_id
486
487 context_dic = [context.copy()]
488- context_dic[0]['export_url'] = True # for the magento version 1.3.2.4, only one url is autorized by product, so we only export with the MAPPING TEMPLATE the url of the default language
489+ context_dic[0]['export_url'] = True # for the magento version 1.3.2.4, only one url is autorized by product, so we only export with the MAPPING TEMPLATE the url of the default language
490 context_dic[0]['lang'] = shop.referential_id.default_lang_id.code
491
492 for storeview in shop.storeview_ids:
493@@ -1499,14 +1498,14 @@
494 result['create_ids'] += temp_result['create_ids']
495 result['write_ids'] += temp_result['write_ids']
496 return result
497-
498+
499 def try_ext_update(self, cr, uid, data, conn, method, oe_id, external_id, ir_model_data_id, create_method, context=None):
500 if context is None: context = {}
501 if context.get('storeview_code', False):
502 return conn.call(method, [external_id, data, context.get('storeview_code', False)])
503 else:
504 return conn.call(method, [external_id, data])
505-
506+
507 def ext_update(self, cr, uid, data, conn, method, oe_id, external_id, ir_model_data_id, create_method, context=None):
508 product = self.browse(cr, uid, oe_id)
509 sku = self.product_to_sku(cr, uid, product)
510@@ -1544,7 +1543,7 @@
511 :return: True
512 """
513 if context is None: context = {}
514- logger = netsvc.Logger()
515+ logger = logging.getLogger('ext synchro')
516
517 shop = self.pool.get('sale.shop').browse(
518 cr, uid, shop_id, context=context)
519@@ -1577,14 +1576,13 @@
520 connection.call('product_stock.update',
521 [mag_product_id, inventory_vals])
522
523- logger.notifyChannel(
524- 'ext synchro',
525- netsvc.LOG_INFO,
526- "Successfully updated stock level at %s for "
527- "product with SKU %s " %
528- (inventory_vals.get('qty', 'N/A'), product.magento_sku))
529+ logger.info(
530+ "Successfully updated stock level at %s for product with SKU %s",
531+ inventory_vals.get('qty', 'N/A'),
532+ product.magento_sku
533+ )
534 return True
535-
536+
537 def ext_assign_links(self, cr, uid, ids, external_referential_ids=None, defaults=None, context=None):
538 """ Assign links of type up-sell, cross-sell, related """
539 if isinstance(ids, (int, long)):
540@@ -1607,7 +1605,7 @@
541 position = position or {}
542 quantities = quantities or {}
543 external_referential_ids = external_referential_ids or []
544- logger = netsvc.Logger()
545+ logger = logging.getLogger('ext assign')
546 conn = context.get('conn_obj', False)
547
548 for ref_id in external_referential_ids:
549@@ -1662,7 +1660,7 @@
550 for c_ext_id in ext_id_to_remove:
551 # remove the product links that are no more setup on openerp
552 conn.call('product_link.remove', magento_args + [c_ext_id])
553- logger.notifyChannel('ext assign', netsvc.LOG_INFO, "Successfully removed assignment of type %s for product %s to product %s" % (type, skus[parent_id], c_ext_id))
554+ logger.info("Successfully removed assignment of type %s for product %s to product %s", type, skus[parent_id], c_ext_id)
555 for child_ext_id in ext_id_to_assign:
556 # assign new product links
557 product_id = new_child_ext_ids[child_ext_id]
558@@ -1671,7 +1669,7 @@
559 [child_ext_id,
560 {'position': position.get(product_id, 0),
561 'qty': quantities.get(product_id, 1)}])
562- logger.notifyChannel('ext assign', netsvc.LOG_INFO, "Successfully assigned product %s to product %s with type %s" %(skus[parent_id], skus[product_id], type))
563+ logger.info("Successfully assigned product %s to product %s with type %s", skus[parent_id], skus[product_id], type)
564 for child_ext_id in ext_id_to_update:
565 # update products links already assigned
566 product_id = new_child_ext_ids[child_ext_id]
567@@ -1680,7 +1678,7 @@
568 [child_ext_id,
569 {'position': position.get(product_id, 0),
570 'qty': quantities.get(product_id, 1)}])
571- logger.notifyChannel('ext assign', netsvc.LOG_INFO, "Successfully updated assignment of type %s of product %s to product %s" %(type, skus[parent_id], skus[product_id]))
572+ logger.info("Successfully updated assignment of type %s of product %s to product %s", type, skus[parent_id], skus[product_id])
573 return True
574
575 #TODO move this code (get exportable image) and also some code in product_image.py and sale.py in base_sale_multichannel or in a new module in order to be more generic
576@@ -1696,7 +1694,7 @@
577
578 def _mag_import_product_links_type(self, cr, uid, product, link_type, external_referential_id, conn, context=None):
579 if context is None: context = {}
580- logger = netsvc.Logger()
581+ logger = logging.getLogger('ext synchro')
582 product_link_obj = self.pool.get('product.link')
583 selection_link_types = product_link_obj._columns['type'].selection(cr, uid, context)
584 # This method could be completed to import grouped products too, you know, for Magento a product link is as
585@@ -1707,7 +1705,7 @@
586 product_links = conn.call('product_link.list', [link_type, product.magento_sku])
587 except Exception, e:
588 self.log(cr, uid, product.id, "Error when retrieving the list of links in Magento for product with sku %s and product id %s !" % (product.magento_sku, product.id,))
589- logger.notifyChannel('ext synchro', netsvc.LOG_DEBUG, "Error when retrieving the list of links in Magento for product with sku %s and product id %s !" % (product.magento_sku, product.id,))
590+ logger.debug("Error when retrieving the list of links in Magento for product with sku %s and product id %s !", product.magento_sku, product.id)
591
592 for product_link in product_links:
593 ctx = context.copy()
594@@ -1729,7 +1727,7 @@
595 product_link_obj.write(cr, uid, existing_link, link_data, context=context)
596 else:
597 product_link_obj.create(cr, uid, link_data, context=context)
598- logger.notifyChannel('Import Product Links', netsvc.LOG_INFO, "Successfully imported product link of type %s on product %s to product %s" %(link_type, product.id, linked_product_id))
599+ logger.info("Successfully imported product link of type %s on product %s to product %s", link_type, product.id, linked_product_id)
600 return True
601
602 def mag_import_product_links_types(self, cr, uid, ids, link_types, external_referential_id, conn, context=None):
603
604=== modified file 'magentoerpconnect/product_images.py'
605--- magentoerpconnect/product_images.py 2011-11-27 15:12:39 +0000
606+++ magentoerpconnect/product_images.py 2012-05-25 09:04:23 +0000
607@@ -23,7 +23,7 @@
608 from osv import osv, fields
609 import magerp_osv
610 import mimetypes
611-import netsvc
612+import logging
613 from tools.translate import _
614
615 #TODO the option small_image, thumbnail, exclude, base_image, should be store diferently indeed this is not compatible with mutli instance (maybe serialized will be a good solution)
616@@ -48,12 +48,12 @@
617 'thumbnail':lambda * a:True,
618 'exclude':lambda * a:False
619 }
620-
621+
622 def get_changed_ids(self, cr, uid, start_date=False):
623 proxy = self.pool.get('product.images')
624 domain = start_date and ['|', ('create_date', '>', start_date), ('write_date', '>', start_date)] or []
625 return proxy.search(cr, uid, domain)
626-
627+
628 def del_image_name(self, cr, uid, id, context=None):
629 if context is None: context = {}
630 image_ext_name_obj = self.pool.get('product.images.external.name')
631@@ -65,7 +65,7 @@
632 def update_remote_images(self, cr, uid, ids, context=None):
633 if context is None:
634 context = {}
635- logger = netsvc.Logger()
636+ logger = logging.getLogger('ext synchro')
637 conn = context.get('conn_obj', False)
638 if not conn:
639 return False
640@@ -112,7 +112,7 @@
641 image_2_date[image['id']] = image['write_date'] or image['create_date']
642 list_date = date_2_image.keys()
643 list_date.sort()
644-
645+
646 ids = [date_2_image[date] for date in list_date]
647
648 while ids:
649@@ -122,24 +122,24 @@
650 ext_file_name = each.oeid_to_extid(context['external_referential_id'])
651 if ext_file_name: #If update
652 try:
653- logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "Updating %s's image: %s" %(each.product_id.magento_sku, each.name))
654+ logger.info("Updating %s's image: %s", each.product_id.magento_sku, each.name)
655 result = update_image(ext_file_name, each)
656- logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "%s's image updated with sucess: %s" %(each.product_id.magento_sku, each.name))
657+ logger.info("%s's image updated with sucess: %s", each.product_id.magento_sku, each.name)
658 need_to_be_created = False
659 except Exception, e:
660- logger.notifyChannel(_("Magento Connection"), netsvc.LOG_ERROR, _("Error in connecting:%s") % (e))
661+ logger.error(_("Error in connecting:%s"), e, exc_info=True)
662 if not "Fault 103" in str(e):
663- logger.notifyChannel(_("Magento Connection"), netsvc.LOG_ERROR, _("Unknow error stop export"))
664+ logger.error(_("Unknow error stop export"))
665 raise
666 else:
667 #If the image was deleded in magento, the external name is automatically deleded before trying to re-create the image in magento
668 model_data_ids = ir_model_data_obj.search(cr, uid, [('model', '=', self._name), ('res_id', '=', each.id), ('external_referential_id', '=', context['external_referential_id'])])
669 if model_data_ids and len(model_data_ids) > 0:
670 ir_model_data_obj.unlink(cr, uid, model_data_ids, context=context)
671- logger.notifyChannel(_("Magento Connection"), netsvc.LOG_ERROR, _("The image don't exist in magento, try to create it"))
672+ logger.error(_("The image don't exist in magento, try to create it"))
673 if need_to_be_created:
674 if each.product_id.magento_sku:
675- logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "Sending %s's image: %s" %(each.product_id.magento_sku, each.name))
676+ logger.info("Sending %s's image: %s", each.product_id.magento_sku, each.name)
677 result = conn.call('catalog_product_attribute_media.create',
678 [each.product_id.magento_sku,
679 {'file':{
680@@ -151,12 +151,12 @@
681 ])
682 self.create_external_id_vals(cr, uid, each.id, result, context['external_referential_id'], context=context)
683 result = update_image(result, each)
684- logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "%s's image send with sucess: %s" %(each.product_id.magento_sku, each.name))
685+ logger.info("%s's image send with sucess: %s", each.product_id.magento_sku, each.name)
686 if image_2_date[each.id] > context['last_images_export_date']: #indeed if a product was created a long time ago and checked as exportable recently, the write date of the image can be far away in the past
687 self.pool.get('sale.shop').write(cr,uid,context['shop_id'],{'last_images_export_date':image_2_date[each.id]})
688 cr.commit()
689 ids = ids[1000:]
690- logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "still %s image to export" %len(ids))
691+ logger.info("still %s image to export", len(ids))
692 return True
693-
694+
695 product_images()
696
697=== modified file 'magentoerpconnect/sale.py'
698--- magentoerpconnect/sale.py 2012-05-24 19:33:15 +0000
699+++ magentoerpconnect/sale.py 2012-05-25 09:04:23 +0000
700@@ -26,6 +26,7 @@
701 import pooler
702 import magerp_osv
703 import netsvc
704+import logging
705 from tools.translate import _
706 import string
707 #from datetime import datetime
708@@ -50,7 +51,7 @@
709
710 class sale_shop(magerp_osv.magerp_osv):
711 _inherit = "sale.shop"
712-
713+
714 def _get_exportable_product_ids(self, cr, uid, ids, name, args, context=None):
715 res = super(sale_shop, self)._get_exportable_product_ids(cr, uid, ids, name, args, context=None)
716 for shop_id in res:
717@@ -70,10 +71,10 @@
718 else:
719 res[shop.id] = False
720 return res
721-
722+
723 def export_images(self, cr, uid, ids, context=None):
724 if context is None: context = {}
725- logger = netsvc.Logger()
726+ logger = logging.getLogger('ext synchro')
727 start_date = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
728 image_obj = self.pool.get('product.images')
729 for shop in self.browse(cr, uid, ids):
730@@ -84,13 +85,13 @@
731 exportable_product_ids = self.read(cr, uid, shop.id, ['exportable_product_ids'], context=context)['exportable_product_ids']
732 res = self.pool.get('product.product').get_exportable_images(cr, uid, exportable_product_ids, context=context)
733 if res:
734- logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "Creating %s images" %(len(res['to_create'])))
735- logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "Updating %s images" %(len(res['to_update'])))
736+ logger.info("Creating %s images", len(res['to_create']))
737+ logger.info("Updating %s images", len(res['to_update']))
738 image_obj.update_remote_images(cr, uid, res['to_update']+res['to_create'], context)
739 self.write(cr,uid,context['shop_id'],{'last_images_export_date': start_date})
740 return True
741-
742-
743+
744+
745 def _get_rootcategory(self, cr, uid, ids, prop, unknow_none, context=None):
746 res = {}
747 for shop in self.browse(cr, uid, ids, context):
748@@ -131,7 +132,7 @@
749 'magento_shop': fields.boolean('Magento Shop', readonly=True),
750 'allow_magento_order_status_push': fields.boolean('Allow Magento Order Status push', help='Allow to send back order status to Magento if order status changed in OpenERP first?'),
751 'allow_magento_notification': fields.boolean('Allow Magento Notification', help='Allow Magento to notify customer with an e-mail when OpenERP change an order status, create an invoice or a delivery order on Magento.'),
752- }
753+ }
754
755 _defaults = {
756 'allow_magento_order_status_push': lambda * a: False,
757@@ -174,7 +175,7 @@
758 conn = shop.referential_id.external_connection()
759 # Update the state of orders in OERP that are in "need_to_update":True
760 # from the Magento's corresponding orders
761-
762+
763 # Get all need_to_update orders in OERP
764 orders_to_update = so_obj.search(
765 cr, uid,
766@@ -239,7 +240,7 @@
767
768 def run_update_images_scheduler(self, cr, uid, context=None):
769 self._sale_shop(cr, uid, self.export_images, context=context)
770-
771+
772 def run_export_shipping_scheduler(self, cr, uid, context=None):
773 self._sale_shop(cr, uid, self.export_shipping, context=context)
774
775@@ -248,7 +249,7 @@
776
777 class sale_order(magerp_osv.magerp_osv):
778 _inherit = "sale.order"
779-
780+
781 _columns = {
782 'magento_incrementid': fields.char('Magento Increment ID', size=32),
783 'magento_storeview_id': fields.many2one('magerp.storeviews', 'Magento Store View'),
784@@ -257,14 +258,14 @@
785 type='boolean',
786 string='Is a Magento Sale Order')
787 }
788-
789+
790 def _auto_init(self, cr, context=None):
791 tools.drop_view_if_exists(cr, 'sale_report')
792 cr.execute("ALTER TABLE sale_order_line ALTER COLUMN discount TYPE numeric(16,6);")
793 cr.execute("ALTER TABLE account_invoice_line ALTER COLUMN discount TYPE numeric(16,6);")
794 self.pool.get('sale.report').init(cr)
795 super(sale_order, self)._auto_init(cr, context)
796-
797+
798 def get_order_addresses(self, cr, uid, referential_id, data_record, context=None):
799 partner_obj = self.pool.get('res.partner')
800 partner_address_obj = self.pool.get('res.partner.address')
801@@ -436,7 +437,7 @@
802 name = product.name
803 if ext_code_field and data_record.get(ext_code_field, False):
804 name = "%s [%s]" % (name, data_record[ext_code_field])
805-
806+
807 if is_tax_included:
808 price_unit = float(amount) + float(data_record[ext_tax_field])
809 else:
810@@ -464,7 +465,7 @@
811 res['order_line'].append((0, 0, extra_line))
812
813 return res
814-
815+
816 def add_order_shipping(self, cr, uid, res, external_referential_id, data_record, defaults, context=None):
817 if context is None: context = {}
818 if data_record.get('shipping_amount', False) and float(data_record.get('shipping_amount', False)) > 0:
819@@ -509,7 +510,7 @@
820 product_ref = ('magentoerpconnect', 'product_product_cash_on_delivery')
821 res = self.add_order_extra_line(cr, uid, res, data_record, 'cod_fee', product_ref, defaults, ctx)
822 return res
823-
824+
825 def convert_extdata_into_oedata(self, cr, uid, external_data, external_referential_id, parent_data=None, defaults=None, context=None):
826 res = super(sale_order, self).convert_extdata_into_oedata(cr, uid, external_data, external_referential_id, parent_data=parent_data, defaults=defaults, context=context)
827 res=res[0]
828@@ -566,7 +567,7 @@
829 all_items.extend(item_modified)
830 else:
831 all_items.append(top_item)
832-
833+
834 data_record['items'] = all_items
835 return data_record
836
837@@ -593,7 +594,7 @@
838 res = super(magerp_osv.magerp_osv, self).oevals_from_extdata(cr, uid, external_referential_id, data_record, key_field, mapping_lines, parent_data, previous_lines, defaults, context)
839
840 #Move me in a mapping
841- if not context.get('one_by_one', False):
842+ if not context.get('one_by_one', False):
843 if data_record.get('status_history', False) and len(data_record['status_history']) > 0:
844 res['date_order'] = data_record['status_history'][len(data_record['status_history'])-1]['created_at']
845 return res
846@@ -653,7 +654,7 @@
847 """
848 if context is None:
849 context = {}
850- logger = netsvc.Logger()
851+ logger = logging.getLogger('ext synchro')
852 conn = context.get('conn_obj', False)
853 parent_list = []
854 # get all parents orders (to cancel) of the sale orders
855@@ -669,7 +670,7 @@
856 try:
857 wf_service.trg_validate(uid, 'sale.order', canceled_order_id, 'cancel', cr)
858 self.log(cr, uid, canceled_order_id, "order %s canceled when updated from external system" % (canceled_order_id,))
859- logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "Order %s canceled when updated from external system because it has been replaced by a new one" % (canceled_order_id,))
860+ logger.info("Order %s canceled when updated from external system because it has been replaced by a new one", canceled_order_id)
861 except osv.except_osv, e:
862 #TODO: generic reporting of errors in magentoerpconnect
863 # except if the sale order has been confirmed for example, we cannot cancel the order
864@@ -744,10 +745,10 @@
865 def ext_set_order_imported(self, cr, uid, external_id, external_referential_id, context=None):
866 if context is None:
867 context = {}
868- logger = netsvc.Logger()
869+ logger = logging.getLogger('ext synchro')
870 conn = context.get('conn_obj', False)
871 conn.call('sales_order.done', [external_id])
872- logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "Successfully set the imported flag on Magento on sale order %s" % external_id)
873+ logger.info("Successfully set the imported flag on Magento on sale order %s", external_id)
874 return True
875
876 def mage_import_base(self, cr, uid, conn, external_referential_id, defaults=None, context=None):
877@@ -774,7 +775,7 @@
878 if context is None:
879 context = {}
880
881- logger = netsvc.Logger()
882+ logger = logging.getLogger('ext synchro')
883 mapping_id = self.pool.get('external.mapping').search(
884 cr, uid,
885 [('model', '=', self._name),
886@@ -792,7 +793,7 @@
887 existing_id = self.extid_to_existing_oeid(cr, uid, ext_order_id, referential_id, context=context)
888 if existing_id:
889 unchanged_ids.append(existing_id)
890- logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "the order %s already exist in OpenERP" % (ext_order_id,))
891+ logger.info("the order %s already exist in OpenERP", ext_order_id)
892 self.ext_set_order_imported(cr, uid, ext_order_id, referential_id, context=context)
893 else:
894 order_ids_filtred.append({'increment_id' : ext_order_id})
895
896=== modified file 'magentoerpconnect/stock.py'
897--- magentoerpconnect/stock.py 2012-05-14 13:22:22 +0000
898+++ magentoerpconnect/stock.py 2012-05-25 09:04:23 +0000
899@@ -20,7 +20,7 @@
900 #########################################################################
901
902 import xmlrpclib
903-import netsvc
904+import logging
905
906 from osv import fields,osv
907 from tools.translate import _
908@@ -38,14 +38,14 @@
909 conn = context.get('conn_obj', False)
910 ext_shipping_id = conn.call('sales_order_shipment.create', [magento_incrementid, {}, _("Shipping Created"), mail_notification, True])
911 return ext_shipping_id
912-
913+
914 def add_picking_line(self, cr, uid, lines, picking_line, context=None):
915 """ A line to add in the shipping is a dict with : product_id and product_qty keys."""
916 line_info = {'product_id': picking_line.product_id.id,
917 'product_qty': picking_line.product_qty,
918 }
919 lines.append(line_info)
920- return lines
921+ return lines
922
923 def create_ext_partial_shipping(self, cr, uid, id, external_referential_id, magento_incrementid, mail_notification=True, context=None):
924 if context is None: context = {}
925@@ -57,7 +57,7 @@
926 product_2_item.update({self.pool.get('product.product').extid_to_oeid(cr, uid, item['product_id'], external_referential_id, context={}): item['item_id']})
927 picking = self.pool.get('stock.picking').browse(cr, uid, id, context)
928 item_qty = {}
929-
930+
931 lines = []
932 # get product and quantities to ship from the picking
933 for line in picking.move_lines:
934@@ -70,7 +70,7 @@
935 item_qty.update({product_2_item[line['product_id']]: line['product_qty']})
936
937 ext_shipping_id = conn.call('sales_order_shipment.create', [magento_incrementid, item_qty, _("Shipping Created"), mail_notification, True])
938- return ext_shipping_id
939+ return ext_shipping_id
940
941 def create_ext_shipping(self, cr, uid, id, picking_type, external_referential_id, context=None):
942 """
943@@ -112,18 +112,18 @@
944
945 def add_ext_tracking_reference(self, cr, uid, id, carrier_id, ext_shipping_id, context=None):
946 if context is None: context = {}
947- logger = netsvc.Logger()
948+ logger = logging.getLogger('ext synchro')
949 conn = context.get('conn_obj', False)
950 carrier = self.pool.get('delivery.carrier').read(cr, uid, carrier_id, ['magento_carrier_code', 'magento_tracking_title'], context)
951-
952+
953 if self.pool.get('ir.model.fields').search(cr, uid, [('name', '=', 'carrier_tracking_ref'), ('model', '=', 'stock.picking')]): #OpenERP v6 have the field carrier_tracking_ref on the stock_picking but v5 doesn't have it
954 carrier_tracking_ref = self.read(cr, uid, id, ['carrier_tracking_ref'], context)['carrier_tracking_ref']
955 else:
956 carrier_tracking_ref = ''
957-
958+
959 res = conn.call('sales_order_shipment.addTrack', [ext_shipping_id, carrier['magento_carrier_code'], carrier['magento_tracking_title'] or '', carrier_tracking_ref or ''])
960 if res:
961- logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "Successfully adding a tracking reference to the shipping with OpenERP id %s and ext id %s in external sale system" % (id, ext_shipping_id))
962+ logger.info("Successfully adding a tracking reference to the shipping with OpenERP id %s and ext id %s in external sale system", id, ext_shipping_id)
963 return True
964
965 stock_picking()