Ravi Gadhia (OpenERP) has proposed merging lp:~openerp-dev/openobject-client/trunk-add-datetime-in-logfile-rga into lp:openobject-client.
Requested reviews: Naresh(OpenERP) (nch-openerp) For more details, see: https://code.launchpad.net/~openerp-dev/openobject-client/trunk-add-datetime-in-logfile-rga/+merge/54338 -- https://code.launchpad.net/~openerp-dev/openobject-client/trunk-add-datetime-in-logfile-rga/+merge/54338 Your team OpenERP R&D Team is subscribed to branch lp:~openerp-dev/openobject-client/trunk-add-datetime-in-logfile-rga.
=== added file 'bin/loglevel.py' --- bin/loglevel.py 1970-01-01 00:00:00 +0000 +++ bin/loglevel.py 2011-03-22 12:37:50 +0000 @@ -0,0 +1,110 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). +# Copyright (C) 2010-2011 OpenERP s.a. (<http://openerp.com>). +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +############################################################################## +import logging +import logging.handlers +import sys +import options +import release + +BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, _NOTHING, DEFAULT = range(10) +#The background is set with 40 plus the number of the color, and the foreground with 30 +#These are the sequences need to get colored ouput +RESET_SEQ = "\033[0m" +COLOR_SEQ = "\033[1;%dm" +BOLD_SEQ = "\033[1m" +COLOR_PATTERN = "%s%s%%s%s" % (COLOR_SEQ, COLOR_SEQ, RESET_SEQ) + +logging.DEBUG_RPC = logging.DEBUG - 1 +logging.addLevelName(logging.DEBUG_RPC, 'DEBUG_RPC') +logging.Logger.debug_rpc = lambda self, msg, *args, **kwargs: self.log(logging.DEBUG_RPC, msg, *args, **kwargs) + +logging.DEBUG_RPC_ANSWER = logging.DEBUG - 2 +logging.addLevelName(logging.DEBUG_RPC_ANSWER, 'DEBUG_RPC_ANSWER') +logging.Logger.debug_rpc_answer = lambda self, msg, *args, **kwargs: self.log(logging.DEBUG_RPC_ANSWER, msg, *args, **kwargs) + +LEVEL_COLOR_MAPPING = { + logging.DEBUG: (BLUE, DEFAULT), + logging.INFO: (GREEN, DEFAULT), + logging.WARNING: (YELLOW, DEFAULT), + logging.ERROR: (RED, DEFAULT), + logging.CRITICAL: (WHITE, RED), + logging.DEBUG_RPC: (BLUE, WHITE), + logging.DEBUG_RPC_ANSWER: (BLUE, WHITE), +} + +DB = '?' + + +class DBFormatter(logging.Formatter): + def format(self, record): + record.dbname = DB + return logging.Formatter.format(self, record) + +class ColoredFormatter(DBFormatter): + def format(self, record): + fg_color, bg_color = LEVEL_COLOR_MAPPING[record.levelno] + record.levelname = COLOR_PATTERN % (30 + fg_color, 40 + bg_color, record.levelname) + return DBFormatter.format(self, record) + +def init_logger(): + import os + # create a format for log messages and dates + format = '[%(asctime)s][%(dbname)s] %(levelname)s:%(name)s:%(message)s' + # add new log levels below DEBUG + if options.options['logging.syslog']: + # SysLog Handler + if os.name == 'nt': + handler = logging.handlers.NTEventLogHandler("%s %s" % (release.description, release.version)) + else: + handler = logging.handlers.SysLogHandler('/dev/log') + format = '%s %s' % (release.description, release.version) \ + + ':[%(dbname)s]:%(levelname)s:%(name)s:%(message)s' + + elif options.options['logging.logfile']: + # LogFile Handler + logf = options.options['logging.logfile'] + try: + dirname = os.path.dirname(logf) + if dirname and not os.path.isdir(dirname): + os.makedirs(dirname) + if options.options['logging.logrotate'] is not False: + handler = logging.handlers.TimedRotatingFileHandler(logf,'D',1,30) + elif os.name == 'posix': + handler = logging.handlers.WatchedFileHandler(logf) + else: + handler = logging.FileHandler(logf) + except Exception, e: + sys.stderr.write("ERROR: couldn't create the logfile directory. Logging to the standard output.\n") + handler = logging.StreamHandler(sys.stdout) + else: + # Normal Handler on standard output + handler = logging.StreamHandler(sys.stdout) + if isinstance(handler, logging.StreamHandler) and not isinstance(handler, logging.handlers.TimedRotatingFileHandler) and getattr(handler.stream, 'isatty', None): + formatter = ColoredFormatter(format) + else: + formatter = DBFormatter(format) + handler.setFormatter(formatter) + + # add the handler to the root logger + logger = logging.getLogger() + logger.handlers = [] + logger.addHandler(handler) === modified file 'bin/modules/gui/main.py' --- bin/modules/gui/main.py 2011-01-27 06:31:03 +0000 +++ bin/modules/gui/main.py 2011-03-22 12:37:50 +0000 @@ -1027,7 +1027,6 @@ self.sig_logout(widget) log_response = rpc.session.login(*res) if log_response == RES_OK: - options.options.save() id = self.sig_win_menu(quiet=False) if id: self.sig_home_new(quiet=True, except_id=id) === modified file 'bin/openerp-client.py' --- bin/openerp-client.py 2011-01-17 19:11:21 +0000 +++ bin/openerp-client.py 2011-03-22 12:37:50 +0000 @@ -33,6 +33,14 @@ import sys import os +IS_USING_PY2EXE = hasattr(sys, "frozen") +if IS_USING_PY2EXE: + # Redirect log to a file. + LOG_FILENAME = os.path.join(os.getcwd(), "openerp-client.log") + logFile = open(os.path.join(LOG_FILENAME), "w") + sys.stderr = logFile + sys.stdout = logFile + import release __author__ = release.author __version__ = release.version @@ -41,12 +49,6 @@ __builtin__.__dict__['openerp_version'] = __version__ import logging -arguments = {} -if sys.platform == 'win32': - arguments['filename'] = os.path.join(os.environ['USERPROFILE'], 'openerp-client.log') - -logging.basicConfig(**arguments) - from distutils.sysconfig import get_python_lib terp_path = os.path.join(get_python_lib(), 'openerp-client') sys.path.append(terp_path) @@ -79,6 +81,8 @@ translate.setlang() import options +from loglevel import init_logger +init_logger() # On first run, client won't have a language option, # so try with the LANG environ, or fallback to english @@ -86,22 +90,9 @@ if not client_lang: client_lang = os.environ.get('LANG', '').split('.')[0] + translate.setlang(client_lang) - -# add new log levels below DEBUG -logging.DEBUG_RPC = logging.DEBUG - 1 -logging.addLevelName(logging.DEBUG_RPC, 'DEBUG_RPC') -logging.Logger.debug_rpc = lambda self, msg, *args, **kwargs: self.log(logging.DEBUG_RPC, msg, *args, **kwargs) - -logging.DEBUG_RPC_ANSWER = logging.DEBUG - 2 -logging.addLevelName(logging.DEBUG_RPC_ANSWER, 'DEBUG_RPC_ANSWER') -logging.Logger.debug_rpc_answer = lambda self, msg, *args, **kwargs: self.log(logging.DEBUG_RPC_ANSWER, msg, *args, **kwargs) - -logging.getLogger().setLevel(getattr(logging, options.options['logging.level'].upper())) - - - import modules import common @@ -131,8 +122,7 @@ try: win = modules.gui.main.terp_main() - if options.options.rcexist: - win.sig_login() + win.sig_login() if os.name == 'nt': from tools.win32 import get_systemfont_style gtk.rc_parse_string(get_systemfont_style()) === modified file 'bin/options.py' --- bin/options.py 2011-01-16 17:39:47 +0000 +++ bin/options.py 2011-03-22 12:37:50 +0000 @@ -26,6 +26,8 @@ import gtk import gettext import release +import logging +import loglevel def get_home_dir(): """Return the closest possible equivalent to a 'home' directory. @@ -101,6 +103,9 @@ 'printer.softpath_html': 'none', 'printer.path': 'none', 'logging.level': 'INFO', + 'logging.logfile': None, + 'logging.logrotate': True, + 'logging.syslog':None, 'logging.output': 'stdout', 'debug_mode_tooltips':False, 'client.default_path': os.path.expanduser('~'), @@ -121,26 +126,50 @@ parser = optparse.OptionParser(version=_("OpenERP Client %s" % openerp_version)) parser.add_option("-c", "--config", dest="config",help=_("specify alternate config file")) parser.add_option("-v", "--verbose", dest="log_level", action='store_const', const="debug", help=_("Enable basic debugging. Alias for '--log-level=debug'")) - parser.add_option("-l", "--log-level", dest="log_level", type='choice', choices=loglevels, default='error', help=_("specify the log level: %s") % ", ".join(loglevels)) + parser.add_option("-l", "--log-level", dest="level", type='choice', choices=loglevels, help=_("specify the log level: %s") % ", ".join(loglevels)) + parser.add_option("--logfile", dest="logfile", help="file where the client log will be stored") + parser.add_option("--no-logrotate", dest="logrotate", action="store_false", + help="do not rotate the logfile") + parser.add_option("--syslog", action="store_true", dest="syslog", + default=False, help="Send the log to the syslog server") parser.add_option("-u", "--user", dest="login", help=_("specify the user login")) parser.add_option("-p", "--port", dest="port", help=_("specify the server port")) parser.add_option("-s", "--server", dest="server", help=_("specify the server ip/name")) + parser.add_option("-w", "--write_to_config", dest="write_to_config", action="store_true", help=_("Save configuration to ~/.openerprc")) (opt, args) = parser.parse_args() - + self.write_to_config = opt.write_to_config self.rcfile = self._get_rcfile(fname, opt.config) - self.load() - - self.options['logging.level'] = opt.log_level - - for arg in ('login', 'port', 'server'): - if getattr(opt, arg): - self.options['login.'+arg] = getattr(opt, arg) - + def command_line_opt(): + for arg in ('login', 'port', 'server'): + if getattr(opt, arg): + self.options['login.'+arg] = getattr(opt, arg) + + for arg in ('syslog', 'logrotate', 'logfile', 'level'): + if getattr(opt, arg): + self.options['logging.'+ arg] = getattr(opt, arg) + + if not os.path.exists(self.rcfile) and not self.write_to_config: + self.save() + + if self.write_to_config: + command_line_opt() + self.load() + else: + self.load() + command_line_opt() + + self.change_loglevel() + + def change_loglevel(self): + logging.getLogger().setLevel(getattr(logging, self.options.get('logging.level','info').upper())) + def _get_rcfile(self, fname, optconfigfile): rcfile = fname or optconfigfile or os.environ.get('OPENERPRC') or os.path.join(get_home_dir(), '.openerprc') if not os.path.exists(rcfile): import logging log = logging.getLogger('common.options') + handler = logging.StreamHandler(sys.stdout) + log.addHandler(handler) additional_info = "" if optconfigfile: additional_info = " Be sure to specify an absolute path name if you are using the '-c' command line switch" @@ -168,11 +197,8 @@ def load(self, fname=None): try: - self.rcexist = False - if not os.path.isfile(self.rcfile): + if self.write_to_config: self.save() - return False - self.rcexist = True p = ConfigParser.RawConfigParser() p.read([self.rcfile]) @@ -202,6 +228,5 @@ options = configmanager() - # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: === modified file 'bin/rpc.py' --- bin/rpc.py 2011-01-06 09:49:16 +0000 +++ bin/rpc.py 2011-03-22 12:37:50 +0000 @@ -25,6 +25,7 @@ import socket import tiny_socket +import loglevel import service import common import options @@ -252,6 +253,7 @@ # exception raised? sock = self._gw(self._url, self.db, self.uid, self._passwd) self.context_reload() + loglevel.DB = self.db return 1 def migrate_databases(self, url, password, databases):
_______________________________________________ Mailing list: https://launchpad.net/~openerp-dev-web Post to : [email protected] Unsubscribe : https://launchpad.net/~openerp-dev-web More help : https://help.launchpad.net/ListHelp

