下面的日志记录代码会将所有日志信息发送到远程服务器,并在终端中打印出来。这里的问题是,如何制作一个全球配置,如" basicConfig"是为了简化每个记录器中的代码。
logger.error("Hey log it's an error", exc_info=True, extra=d)
例如,我想将上面的代码简化为logger.error("嘿记录错误"),默认配置为" exc_info = True,extra = d"
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 :(得分:0)
LoggerAdapter可以轻松解决它。
d = {'clientip': "your ip", 'user': 'logging_test'}
logger = logging.LoggerAdapter(logger, d)