pythonで毎回使いたいloggingモジュールのテンプレート
毎回、どこに書いたか探しているので自分用にメモ
logファイルの初期設定(コマンド引数取らない版)
import os import logging BASE_PATH = os.path.abspath(os.path.dirname(__file__)) logFormat = '[%(asctime)s] %(levelname)s %(message)s' logFilename = 'hogeApp.log' logLevel = logging.INFO logging.basicConfig(level=logLevel, format=logFormat, filename=os.path.join(BASE_PATH,logFilename), filemode='a') logging.debug('current dir: %s'%(os.getcwd())) logging.info('save log file %s'%(os.path.join(BASE_PATH, logFilename)))
logファイルの初期設定(コマンド引数版)
myusage = '%prog [-f filename] [-p portNum] [-debug] recTime(sec)' parser = OptionParser(usage=myusage) parser.add_option('-f', '--file', type = 'string', dest='recFilename', default='hogeApp.log', help='hoge description', metavar='FILE') parser.add_option('-p', '--port', type = 'int', dest='port', default=1, help='serial port number', metavar='INT') parser.add_option('-d', '--debug', action = 'store_true', dest='debug', default=False, help='debug mode') (option, args) = parser.parse_args() # ----- setting log file ----------------------------------------- BASE_DIR = os.path.dirname(os.path.abspath(__file__)) os.chdir(BASE_DIR) logFormat = '[%(asctime)s] %(levelname)s %(message)s' logFilename = r'serialComm.log' # ----- exe ------------------------------------------------------ if len(args) > 0: try: pass #os.spawnv(os.P_NOWAIT, "C:\windows\system32\calc.exe", ["calc.exe"]) except: logging.error('could not execute clac.exe') if option.debug: logLevel = logging.DEBUG else: logLevel = logging.INFO logging.basicConfig(level=logLevel, format=logFormat, filename=os.path.join(BASE_DIR,logFilename), filemode='a') logging.debug('current dir: %s'%(os.getcwd())) logging.info('save log file %s'%(os.path.join(os.getcwd(),option.recFilename))) else: parser.print_help()
でかすぎる・・もっとシンプルな良い方法を知りたい。