Python - 不同日志应该在不同的文件中,但出现在同一个文件
问题描述:
我有一个Web应用程序,具有最小的日志记录功能。后端使用Falcon(在Python上)在Apache上运行。Python - 不同日志应该在不同的文件中,但出现在同一个文件
每个请求具有下面的代码
msg = 'user: {usr} running {req} {req_uri:<30} | from: {loc_ip}:{loc_port} '.format(
usr=req.env['REMOTE_USER'],
req=req.env['REQUEST_METHOD'],
loc_ip=req.env['REMOTE_ADDR'],
loc_port=req.env['REMOTE_PORT'],
req_uri=req.env['REQUEST_URI'])
log_name = 'logs/{remote_ip}/{remote_ip}_{day}.log'.format(remote_ip=req.env['REMOTE_ADDR'], day=datetime.datetime.now().date().strftime('%d_%m_%Y'))
os.makedirs(os.path.dirname(log_name), exist_ok=True)
logging.basicConfig(filename=log_name, level=logging.DEBUG, format='[%(asctime)s] - %(levelname)s - [%(module)s:%(lineno)d] %(message)s', datefmt='%d/%m/%Y %H:%M:%S')
logging.info(msg)
我从2个不同的IP地址(IPX和IPY)访问应用 - 所以应该有下“日志”,文件夹“IPX”和文件夹2夹'IPy',每个文件都有一个日志文件。但是在我访问网页后,我看到2个文件夹,但是其中只有一个文件夹里面有一个日志文件(可以说是IPx文件夹中的IPx_day.log),但在查看了IPx_day.log文件后,我看到:
[TIME] - INFO - [FILE] user: user1 running GET /domain | from: IPy:PORTy
// Other log statments..
[TIME] - INFO - [FILE] user: user2 running GET /domain | from: IPx:PORTx
两行都在文件文件中 - IPx_day.log
有没有人知道为什么两行都出现在同一个文件中?
谢谢。
答
[我想补充一点的评论,但我没有信誉这么做。]
我认为它可能有一些使用只配置根记录器的logging.basicConfig()。我认为你必须使用多个记录器或更好的方法是将多个处理程序附加到一个记录器。
https://docs.python.org/3/library/logging.html#logging.basicConfig https://docs.python.org/3/library/logging.handlers.html
答
从你的文章,我已经明白是
- 您要创建2个不同的文件夹,并在各自的 目录中的日志文件。
- 您从IPx运行应用程序,并且您在IPx.log中看到日志,但在IPy中运行应用程序时看到的日志为 ,IPy的日志在IPx.log中。
如果这是正确的,你能不能请检查是否
- 右键IP [remote_IP]被传递所有的时间?
- 打印IP和log_name,并检查您获得的IP和日志目录。
我想,路径变化是必需的。除非你的基本路径是[脚本的源]