Django ブログサイト log.py ログ共通処理
2020/07/04 (更新:2020/11/19)
本サイトは、Django の標準ライブラリloggingでログを出力します。
本処理は、当該ライブラリを拡張し共通で出力する項目を追加します。
| 項目 | フォーマット | 説明 |
|---|---|---|
| clientIp | %(clientIp)s | クライアントのIPアドレス |
| requestPath | %(requestPath)s | リクエストのURLパス |
ログの設定は、settingに定義します。
LogMiddlewareはsettings.MIDDLEWAREに定義します。
log.py
old_factory = logging.getLogRecordFactory()
threadinglocal = threading.local()
def record_factory(*args, **kwargs):
record = old_factory(*args, **kwargs)
clientIp, requestPath = '', ''
if hasattr(threadinglocal, 'request'):
clientIp = get_client_ip(threadinglocal.request)[0]
requestPath = threadinglocal.request.path
record.clientIp = clientIp
record.requestPath = requestPath
return record
logging.setLogRecordFactory(record_factory)
class LogMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
threadinglocal.request = request
return self.get_response(request)
settings
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(asctime)s %(process)d %(thread)d %(clientIp)-15s %(levelname)-5s %(name)s.%(funcName)s %(message)s'
},
'simple': {
'format': '%(asctime)s %(levelname)-5s %(name)s.%(funcName)s %(message)s'
},
'operation': {
'format': '%(asctime)s %(clientIp)-15s %(requestPath)s %(message)s'
},
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose',
},
'operation': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'operation',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'INFO',
},
'blog': {
'handlers': ['console'],
'level': 'DEBUG',
},
'blog.operation': {
'handlers': ['operation'],
'level': 'INFO',
},
}
}
from .. import log