2017-03-21 6 views
0

以下のようなロギングコードは、すべてのログ情報をリモートサーバに送信し、それらを端末にプリントアウトします。ここでの質問は、 "basicConfig"のような抽象的な設定を行う方法は、各ロガーのコードを単純化することです。例えばexc_infoとロギングのためのグローバル設定を行うためのよりよい解決法があります

logger.error("Hey log it's an error", exc_info=True, extra=d) 

、私は「exc_info = Trueの場合、余分= D」のデフォルトの設定で(「ねえ、それはエラーのログ」)logger.errorに上記のコードを簡素化します。

import logging 
import threading 
import time 
import logging.handlers 

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(pathname)s - %(filename)s - %(module)s - %(lineno)d - %(process)d - (%(threadName)-10s) - %(levelname)s - %(message)s',) 
logger = logging.getLogger(__name__) 
http_handler = logging.handlers.HTTPHandler(
    'ip:port', 
    '/log', 
    method='POST', 
) 
logger.addHandler(http_handler) 

d = {'clientip': "your ip", 'user': 'logging_test'} 

class ThreadUrl(threading.Thread): 
    def run(self): 
     logger.debug("Hey log it's a debug", extra=d) 
     try: 
      open('testfile') 
     except Exception, e: 
      logger.error("Hey log it's an error", exc_info=True, extra=d) 


for i in range(10): 
    t = ThreadUrl() 
    t.start() 
    time.sleep(1) 

サンプルがMongoDBにあります。

{ 
    "_id" : ObjectId("58d1326215109901ce525da4"), 
    "relativeCreated" : "9132.83205032", 
    "process" : "57540", 
    "CreateDate" : ISODate("2017-03-21T04:51:24.065+08:00"), 
    "args" : "()", 
    "module" : "Logging_inspect", 
    "funcName" : "run", 
    "user" : "logging_test", 
    "exc_text" : "None", 
    "clientip" : "your ip", 
    "name" : "__main__", 
    "thread" : "123145406930944", 
    "created" : "1490076138.79", 
    "threadName" : "Thread-10", 
    "msecs" : "790.709972382", 
    "filename" : "Logging_inspect.py", 
    "levelno" : "40", 
    "processName" : "MainProcess", 
    "pathname" : "/Users/user/Desktop/Test/Test/Logging_inspect.py", 
    "lineno" : "25", 
    "msg" : "Hey log it's an error", 
    "exc_info" : "(<type 'exceptions.IOError'>, IOError(2, 'No such file or directory'), <traceback object at 0x10419c248>)", 
    "levelname" : "ERROR" 
} 
+0

なぜあなたはLogger' 'から基底クラスを使用して独自のロガークラスを作成し、あなたが正しいですが、私はメソッドをオーバーライドする方法についての混乱を感じる@saurabhbaid必要 –

+0

などのメソッドをオーバーライドしていけません。私にそれについてのより多くのヒントを与えることができますか?ありがとう! –

+0

小さなGoogleは、あなたの下に1つのようにそれについてたくさんのtutotialを与えることができますhttp://blog.thedigitalcatonline.com/blog/2014/05/19/method-overriding-in-python/#.WNDKdFWGOpo –

答えて

0

LoggerAdapterは簡単に解決できます。

d = {'clientip': "your ip", 'user': 'logging_test'} 
logger = logging.LoggerAdapter(logger, d) 
関連する問題