在python和django中使用日志记录用户与网站的交互

问题描述:

我目前正在帮助开发一个网站。上周末有人企图侵入网站,但失败了。但是,由于去年夏天整个网站都被重写了,所以没有办法在网站中存储他们的动作,并在用户放弃之前捕捉用户的IP。在python和django中使用日志记录用户与网站的交互

有没有一种方法可以跟踪用户在网站中的操作(例如他们访问的链接)并将其存储到文件中(网站很小),以确保我们记录了操作,如果有人曾试图再次入侵它?

为了看看我是否可以做到这一点,我开始使用日志记录,但遇到了我应该如何记录用户日志记录操作的问题。我的设置是在下面,它的工作原理,我只是不知道要在logging.info()中的当前字符串中放置什么来记录用户的移动。预先感谢您提供的任何帮助。

from ipware.ip import get_ip 
import logging 

def IPCatcher(request): 
    ip = get_ip(request) 
if ip is not None: 
    print("We have an IP address for user") 
    print(ip) 
    logging.basicConfig(filename='log_recording.txt', 
         level=logging.DEBUG,format='%(asctime)s %(message)s', 
                  datefmt='%m/%d/%Y %I:%M:%S %p') 
    logging.info('This is working') 

else: 
    print("we don't have an IP address for user") 
+0

你使用的是Apache还是nginx? –

+0

现在我没有使用Apache,因为安全性,我正在考虑nginx,但目前还没有使用。 nginx会在这种情况下提供帮助吗? – scottyboy

记录在Django可以在第一是相当艰巨的,但有很多对网络上阅读了。为了给您一个概述,设置logging in django的最简单方法是从配置日志的settings.py文件开始;

LOGGING = { 
    'version': 1, 
    'disable_existing_loggers': False, 
    'handlers': { 
     'file': { 
      'level': 'DEBUG', 
      'class': 'logging.FileHandler', 
      'filename': '/path/to/django/debug.log', 
     }, 
     'mail_admins': { 
      'level': 'ERROR', 
      'class': 'django.utils.log.AdminEmailHandler', 
     } 
    }, 
    'loggers': { 
     'django': { 
      'handlers': ['file'], 
      'level': 'DEBUG', 
      'propagate': True, 
     }, 
     'my_app': { 
      'handlers': ['file'], 
      'level': 'DEBUG', 
      'propagate': True, 
     }, 
    }, 
} 

替换my_app与应用标签&然后在视图中的日志记录调用将记录到file处理程序(注意mail_admins处理程序将发送电子邮件至settings.ADMINS)。

import logging 

from ipware.ip import get_ip 

# This gets a named logger, which should match your appname 
logger = logging.getLogger(__name__) 

def IPCatcher(request): 
    ip = get_ip(request) 
    if ip is not None: 
     logger.info('This is working') 

我也推荐看这个教程的主题; https://www.youtube.com/watch?v=BsbtPqQdo3Q

+1

非常感谢您的帮助! – scottyboy

+0

@scottyboy我也想添加,你可以使用类似于apache日志的旋转文件。看看这里; https://djangosnippets.org/snippets/2980/ –