在多进程下 使用logging模块是不安全的,在多线程下是没有问题的,会报以下错误
如果你是在使用pycharm开发而且是单线程的话,请产考另外一篇文章 添加--noreload参数解决。该方法多线程程序不适用
PermissionError: [WinError 32] 另一个程序正在使用此文件,进程无法访问。: 'c:\\python\\opskb\\logs\\default\\default.log' -> 'c:\\python\\opskb\\logs\\default\\default.log.1'
解决办法把logging.handlers.RotatingFileHandler 替换成我们今天的主角cloghandler.ConcurrentRotatingFileHandler
首现这个模块是需要单独安装的
pip install ConcurrentLogHandler
如果你是windows系统确保win32安装了
pip install pywin32
编辑settings.py文件
首现导入模块
import cloghandler
import logging.config
修改配置文件,修改handlers中的class
logging.config.dictConfig({
………
'handlers': {
'public': {
'level': 'DEBUG',
'class': 'cloghandler.ConcurrentRotatingFileHandler',
'filename': f'{BASE_DIR}/logs/public/public.log',
'maxBytes': 1024*1024*5,
'backupCount': 5,
'formatter': 'standard',
},
},
………
})
注:
1、以上程序在linux系统下运行是没有问题,如果在windos平台上会发现无法写入日志,这是因为文件锁问题,我们使用另外一个模块,基于这个模块改善这个问题concurrent-log-handler
pip install concurrent-log-handler
下面给出我系统上完整的配置文件,django的settings.py
import logging.config
import concurrent_log_handler
import logging
import logging.handlers
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': '%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] [%(module)s:%(funcName)s] '
'[%(levelname)s]- %(message)s'} #日志格式
},
'filters': {
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'include_html': True,
},
'public': {
'level': 'DEBUG',
'class': 'concurrent_log_handler.ConcurrentRotatingFileHandler',
'filename': f'{BASE_DIR}/logs/public/public.log',
'maxBytes': 1024*1024*5,
'backupCount': 5,
'formatter': 'standard',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'standard'
},
'vmware': {
'level': 'DEBUG',
'class': 'concurrent_log_handler.ConcurrentRotatingFileHandler',
'filename': f'{BASE_DIR}/logs/vmware/vmware.log',
'maxBytes': 1024*1024*5,
'backupCount': 5,
'formatter': 'standard',
},
'default': {
'level': 'DEBUG',
'class': 'concurrent_log_handler.ConcurrentRotatingFileHandler',
'filename': f'{BASE_DIR}/logs/default/default.log',
'maxBytes': 1024*1024*5,
'backupCount': 5,
'delay': True,
'formatter': 'standard',
}
},
'loggers': {
'django': {
'handlers': ['default', 'console'],
'level': 'DEBUG',
'propagate': False
},
'punlic.proxy': {
'handlers': ['default', 'console'],
'level': 'DEBUG',
'propagate': False,
},
'wmware.getkb': {
'handlers': ['vmware', 'console'],
'level': 'DEBUG',
'propagate': False,
}
}
})
在Views或这个其他需要写日志的地方使用
import logging
logger = logging.getLogger('wmware.getkb')
logger.debug("调试信息")
logger.info("普通消息")
logger.warning("警告信息")
logger.critical("严重信息")
logger.error("错误信息")
文章末尾固定信息
评论